在Python中比较两个.txt文件并将精确和相似匹配保存到.txt文件中

0 投票
2 回答
529 浏览
提问于 2025-04-16 21:02

我需要的是:

text_file_1.txt:
apple
orange
ice
icecream

text_file_2.txt:
apple
pear
ice

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

apple
ice

(相当于 re.match 的效果)

但我想要得到的是:

apple
ice
icecream

(相当于 re.search 的效果)

有没有办法做到这一点?文件很大,所以我不能只是一遍遍地去查找并使用正则表达式。

2 个回答

2

你可能想看看 difflib 这个库。

1

如果你只是想从文件中提取那些彼此之间有部分相同的单词(包括完全相同的单词),你可以这样做:

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库中的某个类:

import difflib as dl

fone = set(['apple', 'orange', 'ice', 'icecream'])
ftwo = set(['apple' ,'pear' ,'ice'])

result = []
for wone in fone:
    for wtwo in ftwo:
        s = dl.SequenceMatcher(None, wone, wtwo)
        if s.ratio() > 0.6:  #0.6 is the conventional threshold to define "close matches"
            result.append(wone)
            result.append(wtwo)
for w in set(result):
    print w

我没有对这两个例子进行计时,但我猜第二个方法会慢很多,因为对于每一对单词,你都需要创建一个对象……

撰写回答