替換我有文件,其中包含句子:查找下一個字並在文件
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
任何想法爲什麼?