Python 比较列表中的单词而不是字母-从SequenceMatcher包获得意外输出
我正在从事一个项目,该项目从我存储在2个文本文件(Python 比较列表中的单词而不是字母-从SequenceMatcher包获得意外输出,python,string,Python,String,我正在从事一个项目,该项目从我存储在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 SequenceMatch
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将它们的相似性评级为.35,但它们除了第一个之外并没有太大的相似性。我有一种暗示,这是因为SequenceMatcher通过字母而不是单词来判断相似性。有人知道如何标记标题中的单词,以便SequenceMatcher将它们作为整个单词而不是单个字母来阅读吗?你的直觉很可能是正确的。您看到的匹配是基于不间断的匹配字母字符串,这通常是一个非常糟糕的标题相似性度量 这样做是因为你传递的序列是一个字符串,或者在计算机看来,是一个很长的字母列表 如果您想根据单词进行判断,我建议使用
.split()
函数拆分文本,该函数只会根据空格进行拆分
您可以而且可能应该做很多清理工作,例如,将所有内容都设置为小写('.lower()'),以及潜在地获得合理的匹配。也就是说,所有这些部分都在别处有很好的文档记录,对于您的特定用例可能没有意义
您也可以在
sklearn
中查看其他标记化程序,但它们不太可能在这里产生巨大的影响。在传递文本之前,先调用.split()。非常感谢您提供的有用建议!