2016-02-17 378 views
0

我正在嘗試讀取一個文本文件並將該文件的內容轉換爲拉丁文件的新文件。這裏是我有:讀取和寫入文件

def pl_line(word): 
    statement = input('enter a string: ') 

    words = statement.split() 

    for word in words: 
     if len(word) <= 1: 
      print(word + 'ay') 
     else: 
      print(word[1:] + word[0] + 'ay') 


def pl_file(old_file, new_file): 
    old_file = input('enter the file you want to read from: ') 
    new_file = input('enter the file you would like to write to: ') 

    write_to = open(new_file, 'w') 
    read_from = open(old_file, 'r') 

    lines = read_from.readlines() 
    for line in lines(): 
     line = pl_line(line.strip('\n')) 
     write_to.write(line + '\n') 
    read_from.close() 
    write_to.close() 

然而,當我運行它,我得到這個錯誤信息: 類型錯誤:「名單」對象不是可調用

如何提高我的代碼的任何想法?

回答

0

您很可能混淆了read_fromwrite_to的分配,因此您無意中試圖從僅爲寫入訪問打開的文件中讀取數據。

+0

你是對的,我已經編輯我原來的問題與我提出了與 – holaprofesor

+0

問題的新錯誤消息調用'lines'( 'for'子句中的括號)。通過閱讀整個回溯過程,你可以很容易地發現這一點;它會指向堆棧中發生錯誤的任何代碼的行號。從最後列出的代碼地方開始,如果您沒有看到問題的原因,請按照回溯的方式進行操作。 –

2

下面是實際的轉換器的一些改進:

_VOWELS = 'aeiou' 
_VOWELS_Y = _VOWELS + 'y' 
_SILENT_H_WORDS = "hour honest honor heir herb".split() 

def igpay_atinlay(word:str, with_vowel:str='yay'): 
    is_title = False 
    if word.title() == word: 
     is_title = True 
     word = word.lower() 

    # Default case, strangely, is 'in-yay' 
    result = word + with_vowel 

    if not word[0] in _VOWELS and not word in _SILENT_H_WORDS: 
     for pos in range(1, len(word)): 
      if word[pos] in _VOWELS: 
       result = word[pos:] + word[0:pos] + 'ay' 
       break 

    if is_title: 
     result = result.title() 

    return result 

def line_to_pl(line:str, with_vowel:str='yay'): 
    new_line = '' 

    start = None 
    for pos in range(0, len(line)): 
     if line[pos].isalpha() or line[pos] == "'" or line[pos] == "-": 
      if start is None: 
       start = pos 
     else: 
      if start is not None: 
       new_line += igpay_atinlay(line[start:pos], with_vowel=with_vowel) 
       start = None 
      new_line += line[pos] 

    if start is not None: 
     new_line += igpay_atinlay(line[start:pos], with_vowel=with_vowel) 
     start = None 

    return new_line 

tests = """ 
Now is the time for all good men to come to the aid of their party! 
Onward, Christian soldiers! 
A horse! My kingdom for a horse! 
Ng! 
Run away! 
This is it. 
Help, I need somebody. 
Oh, my! 
Dr. Livingston, I presume? 
""" 

for t in tests.split("\n"): 
    if t: 
     print(t) 
     print(line_to_pl(t))