比较Python中的两个.txt文件并保存与.txt fi完全相同的匹配项

2024-04-23 22:28:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要的是:

text_file_1.txt:
apple
orange
ice
icecream

text_file_2.txt:
apple
pear
ice

当我使用“set”时,输出将是:

^{pr2}$

(“相当于重新匹配“)

但我想得到:

apple
ice
icecream

(“相当于搜索“)

有什么办法吗?文件很大,所以我不能只迭代它并使用regex。在


Tags: 文件texttxtappleregexfilepearset
2条回答

如果您只想从文件中提取一个单词作为另一个单词的子字符串(包括相同的单词),您可以:

fone = set(['apple', 'orange', 'ice', 'icecream'])
ftwo = set(['apple' ,'pear' ,'ice'])
# transforming to sets saves to check twice for the same combination

result = []
for wone in fone:
    for wtwo in ftwo:
        if wone.find(wtwo) != -1 or wtwo.find(wone) != -1:
            result.append(wone)
            result.append(wtwo)
for w in set(result):
    print w

或者,如果您希望基于字符串在字母顺序上的相似性,您可以使用Paul在其回答中建议的difflib提供的类之一:

^{pr2}$

我没有计时两个样本中的任何一个,但我想第二个会运行得慢得多,因为每对样本你都要实例化一个对象。。。在

您可能想签出difflib

相关问题 更多 >