我有两个文件,我试图在两个文件之间打印唯一的句子。为此,我在python中使用difflib。
text ='Physics is one of the oldest academic disciplines. Perhaps the oldest through its inclusion of astronomy. Over the last two millennia. Physics was a part of natural philosophy along with chemistry.'
text1 ='Physics is one of the oldest academic disciplines. Physics was a part of natural philosophy along with chemistry. Quantum chemistry is a branch of chemistry.'
import difflib
differ = difflib.Differ()
diff = differ.compare(text,text1)
print '\n'.join(diff)
它没有给我想要的输出。它给我这样的。
P
h
y
s
i
c
s
i
s
o
n
e
o
f
t
h
e
我想要的输出只是两个文件之间唯一的句子。
文字=也许是最古老的,因为它包含了天文学。在过去的两千年中。
text1 =量子化学是化学的一个分支。
也似乎difflib.Differ逐行而不是句子。请提出任何建议。我该怎么做?
实际上,首先,Differ()。compare()比较行而不是句子。
其次,它实际上比较序列,例如字符串列表。但是,您传递两个字符串,而不是两个字符串列表。由于字符串也是(字符)序列,因此您的情况下Differ()。compare()会比较各个字符。
如果要按句子比较文件,则必须准备两个句子列表。您可以使用nltk.sent_tokenize(text)将字符串拆分为句子。
diff = differ.compare(nltk.sent_tokenize(text),nltk.sent_tokenize(text1))
print('\n'.join(diff))
# Physics is one of the oldest academic disciplines.
#- Perhaps the oldest through its inclusion of astronomy.
#- Over the last two millennia.
# Physics was a part of natural philosophy along with chemistry.
#+ Quantum chemistry is a branch of chemistry.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句