找到下一个单词并替换文件

时间:2016-12-15 05:43:11

标签: file python-3.x

我的文件包含句子:

File1.txt:
"I like Banana"

我想在“喜欢”之后找到这个词并替换它。我尝试使用字符串并且工作正常

String = "orange"
Text = 'I like Banana'
list_of_words = Text.split()
for u, word in enumerate(list_of_words):
    if 'like ' == word:
        next_word= list_of_words[u+ 1] 
        Text = Text.replace(next_word,String)
print(Text)

打印:I like orange

但是当我将其应用于文件时,它只会替换(例如)

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

for line in read_file:
    words = line.split()
    output_line = []
    for u,word in  enumerate(words):
        if 'like' == word:
            new_word = words[u + 1] 
            word = word.replace(new_word,"Orange")
            output_line.append(word)
#--------------------------------------------------------

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

取代与橙色相似:

I Orange Banana

知道为什么吗?!!!!

2 个答案:

答案 0 :(得分:1)

试试这个:

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:
            words[u + 1] = 'Orange'
#--------------------------------------------------------

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

我删除了一些不必要的列表。

答案 1 :(得分:1)

在你的if条件下,你会将单词与单词混淆。你替换'喜欢',而不是['我','喜欢','香蕉']。由于喜欢不包含'oranges',所以该行是no-op。

我想你想要更像这样的东西。虽然这仍然需要检查边界(如果u + 1超出范围怎么办?)。

output_line = []
for line in read_file:
    words = line.split()
    for u,word in  enumerate(words):
        if 'like' == word:
            words[u + 1] = 'Orange'
    output_line.append(' '.join(words))
祝你好运!