2016-02-17 382 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))