替换python

时间:2017-06-07 11:37:31

标签: python text replace

我有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.

我需要在第二个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)

2 个答案:

答案 0 :(得分:1)

首先,您必须使用any而不是all。因为您希望其中至少有一个人在rules进行更改。 然后rule未在if之外定义,另外您可能会在rules中添加line中的多个单词,因此最好迭代rules需要时更换。这给出了:

with open(second, 'r') as secondfile:
    with open(third, 'w') as thirdfile:
        for line in secondfile:
            if any(rule in line for rule in rules):
                for r in rules:
                    line = line.replace(r, '<font color=yellow>'+r+'</font>')
            thirdfile.write(line)

答案 1 :(得分:0)

您希望any代替all,因为rules中的一个单词就足以显示在一行中。