Skip to main content
 首页 » 编程设计

python之比较列表中的单词而不是字母之从 SequenceMatcher 包中获得意外输出

2025年05月04日15zhujiabin

我正在做一个项目,它从我存储在 2 个文本文件(nyt.text 和 wapo.text)中的报纸网站获取标题并比较它们相互比较,如果字符串被 Python 内置的 SequenceMatcher 确定为相似,则将它们连同它们的相似性评级打印给我:

from difflib import SequenceMatcher 
 
f = open('nyt.text','r+') 
w = open('wapo.text','r+') 
 
def similar(a, b): 
return SequenceMatcher(None, a, b).ratio() 
 
 
def compare(self): 
    wapo = [] 
    times = [] 
    for line in w.readlines(): 
        wapo.append(line) 
    for i in f.readlines(): 
        times.append(i) 
    print(wapo[0],times[0]) 
    for i in wapo: 
        for s in times: 
            print(similar(i,s)) 
            if similar(i,s) > 0.35: 
                print(i,s) 
    return 
 
compare() 

我得到的结果看起来像这样:

    Attorney for San Bernardino gunman's family floats hoax theory 
 Op-Ed Contributor: A Battle in San Bernardino 
 
San Bernardino attacker pledged allegiance to Islamic State leader, officials say 
 Sunday Routine: How Jamie Hodari, Workplace Entrepreneur, Spends His Sundays 
 
Why some police departments let anyone listen to their scanner conversations - even criminals 
 White House Seeks Path to Executive Action on Gun Sales 
 
Why the Pentagon opening all combat roles to women could subject them to a military draft 
 Scientists Seek Moratorium on Edits to Human Genome That Could Be Inherited 
 
Destroying the Death Star was a huge mistake 
 Mark Zuckerberg Defends Structure of His Philanthropic Outfit 

如您所见,尽管 SequenceMatcher 将相似度评为 0.35,但除了第一个之外,它们并不太相似。我有一种暗示,这是因为 SequenceMatcher 通过字母而不是单词来判断相似性。有没有人知道如何标记标题中的单词,以便 SequenceMatcher 将它们作为整个单词而不是单个字母来读取?

请您参考如下方法:

您的直觉很可能是正确的。您看到的是基于不间断的匹配字母字符串的匹配,这通常是标题相似性的一个非常差的指标。

它这样做是因为您传入的序列是一个字符串,或者如计算机所见,是一个非常长的字母列表。

如果您想根据单词进行判断,我建议使用 .split() 函数拆分文本,该函数只会按空格拆分。

您可以而且可能应该做很多清洁工作,例如 removing punctuation , 将所有内容设置为小写 ('.lower()'),以及潜在的 stemming the words以获得合理的匹配。也就是说,所有这些部分在其他地方都有详细记录,可能对您的特定用例没有意义。

您还可以查看 sklearn 中的其他分词器,但它们不太可能在这里产生巨大差异。