【问题标题】:Replace words taken from the list in txt file in python [closed]替换python中txt文件中列表中的单词[关闭]
【发布时间】: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)

【问题讨论】:

  • secondthird 之后不应该有任何'
  • 抱歉拼写错误。在我的代码中我没有它们。它不是文件名的情况:) 但谢谢!
  • if all 行正在检查是否所有单词都存在于一行中,然后尝试使用不应在该范围内定义的变量“规则”。你想要for,而不是if all...

标签: python text replace


【解决方案1】:

您希望any 而不是all,因为rules 中的一个 字词出现在一行中就足够了。

【讨论】:

    【解决方案2】:

    首先,您必须使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 2014-03-11
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      相关资源
      最近更新 更多