【发布时间】:2017-11-08 17:50:10
【问题描述】:
我有一个 txt 文件,每行有一个单词 (library.txt),例如:
Word1
Word2
第二个 txt 文件如下所示:
I have got many words.
I know Word1 is very interesting.
ButWord2 is awful because its connected with another word.
I think there is no Word3 at all.
我需要从 Second txt 文件中的 library.txt 中搜索这些单词并替换它们,以便它们看起来像这样:
I have got many words.
For example <font=yellow>Word1</font> is very interesting.
But<font=yellow>Word2</font> is awful because its connected with another word.
I think there is no Word3 at all.
我有这样的代码,但它不起作用:
rules =[]
with open(library, 'r') as libraryfile:
for line in libraryfile:
rules.append(line.rstrip())
with open(second', 'r') as secondfile:
with open(third', 'w') as thirdfile:
for line in secondfile:
if all(rule in line for rule in rules):
thirdfile.write(line.replace(rule, '<font color=yellow>'+rule+'</font>'))
else:
thirdfile.write(line)
【问题讨论】:
-
在
second和third之后不应该有任何'。 -
抱歉拼写错误。在我的代码中我没有它们。它不是文件名的情况:) 但谢谢!
-
您
if all行正在检查是否所有单词都存在于一行中,然后尝试使用不应在该范围内定义的变量“规则”。你想要for,而不是if all...。