用第三个单词替换两个文本文件中常见的单词

时间:2017-08-31 10:53:16

标签: python replace

我有两个文本文件1.txt是单词的字典,另一个是带有短语的2.txt现在我想查看1.txt&中的常用单词。 2.txt和我想用第三个单词替换那些常用单词"解释"。

我尝试了很多方法来破解但失败了。任何人都可以帮助我

我用过的代码:

wordsreplace = open("1.txt",'r')

with open("2.txt") as main:
    words = main.read().split()

replaced = []
for y in words:
    if y in wordreplace:
        replaced.append(wordreplace[y])
    else:
        replaced.append(y)
text = ' '.join(replaced)

replaced = []
for y in words:
    replacement = wordreplace.get(y, y)
    replaced.append(replacement)
text = ' '.join(replaced)

text = ' '.join(wordreplace.get(y, y) for y in words)

new_main = open("2.txt", 'w')
new_main.write(text)
new_main.close()

此代码写入2.txt但我不能替换单词

1 个答案:

答案 0 :(得分:1)

我不想在你的代码中指出问题,因为这个任务基本上可以在几行中完成。这是一个自包含的示例(没有文件,只有文本输入)

  • 首先创建一个名为set的{​​{1}},您可以在需要时进行查询(将words传递给read().split()将从文件中完成:set()
  • 现在使用字边界词正则表达式替换函数

如果在字典中没有找到替换函数,则会发出“解释”:

words = set(main.read().split())

因此,替换是由正则表达式引擎处理的,当匹配时调用我的words = {"computer","random"} text = "computer sometimes yields random results" import re new_text = re.sub(r"\b(\w+)\b",lambda m : "explain" if m.group(1) in words else m.group(1),text) print(new_text) ,因此我可以决定是替换该单词,还是重新发回。

结果:

lambda

当然,这并不能处理必须在字典中的复数(计算机......)。