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



我有两个文本文件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,但我无法替换

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

  • 首先创建一个名为wordsset您可以在需要时查找(将read().split()传递给set()时将在文件中完成时会执行:words = set(main.read().split())
  • 现在使用A 单词式词性正则替换功能

替换功能会发出单词,如果在字典中找不到的话,它会发出"解释":

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)

因此,替换是由Regex引擎处理的,在有匹配时打电话给我的lambda,因此我可以决定是替换单词还是再次发出。

结果:

explain sometimes yields explain results

当然,这也不处理词典中的复数(计算机,...)。

最新更新