2017-02-18 94 views
0

我有一个文本文件包含一个关于故事的文本,我想找到一个单词“like”并获取它后面的下一个单词,并调用一个函数来查找该单词的同义词。这里是我的代码:无法正确保存文件

file = 'File1.txt' 
with open(file, 'r') as open_file: 
    read_file = open_file.readlines() 
    output_lines = []   

for line in read_file: 
    words = line.split() 
    for u, word in enumerate(words): 
     if 'like' == word: 
      next_word = words[u + 1] 
      find_synonymous(next_word) 

    output_lines.append(' '.join(words)) 
    with open(file, 'w') as open_file: 
     open_file.write(' '.join(words)) 

我的,我认为在文本中唯一的问题,因为当我写一个句子包括单词(像)它的工作原理(for example 'I like movies')。但是当我有一个文件包含很多句子并运行代码时,它会删除所有文本。谁能知道哪里可能是问题

回答

0

你有几个问题。 find_synonymous(next_word)不会替换列表中的单词,所以充其量只会返回原始文本。您在for循环内执行open(file, 'w'),因此每行都会覆盖该文件。如果like碰巧是线上的最后一个字,并且您不处理在下一行继续所喜欢的事情的情况,则next_word = words[u + 1]将引发索引错误。

在这个例子中,我追踪“is_liked”状态。如果一个单词处于相同的状态,它将被转换。这样,您可以处理跨行分割的句子,而不必担心索引错误。该列表被写入循环外部的文件。

file = 'File1.txt' 
with open(file, 'r') as open_file: 
    read_file = open_file.readlines() 

output_lines = []   
is_liked = False 

for line in read_file: 
    words = line.split() 
    for u, word in enumerate(words): 
     if is_liked: 
      words[u] = find_synonymous(word) 
      is_liked = False 
     else: 
      is_liked = 'like' == word 
    output_lines.append(' '.join(words) + '\n') 

with open(file, 'w') as open_file: 
    open_file.writelines(output_lines)