两个字符串(句子)之间的差异

2024-04-26 20:34:45 发布

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

我试图计算两个句子之间的差异,如下所示:

import difflib

text1_lines = "I understand how customers do their choice. Difference"
text2_lines = "I understand how customers do their choice."
diff = difflib.ndiff(text1_lines, text2_lines)

我想要一个不同的

但我不明白。我做错什么了?谢谢你让我知道。在


Tags: importdiff差异do句子howlineschoice
3条回答

使用简单的列表理解:

diff = [x for x in difflib.ndiff(text1_lines, text2_lines) if x[0] != ' ']

它会给你看删节和附录

输出:

^{pr2}$

(后面带负号的所有内容都被删除)

相反,切换text1_linestext2_lines会产生这样的结果:

['+  ', '+ D', '+ i', '+ f', '+ f', '+ e', '+ r', '+ e', '+ n', '+ c', '+ e']

要删除标志,可以转换以上列表:

diff_nl = [x[2] for x in diff]

要完全转换为字符串,只需使用.join()

diff_nl = ''.join([x[2] for x in diff])

把大的绳子和小的绳子分开,你就会得到不同的结果。在

if len(a) == 0:
   print b
   return
if len(b) == 0:
   print a
   return
if len(a)>len(b): 
   res=''.join(a.split(b))             #get diff
else: 
   res=''.join(b.split(a))             #get diff

print(res.strip())     

Docs

import difflib
import sys

text1_lines = "I understand how customers do their choice. Difference"
text2_lines = "I understand how customers do their choice."
diff = difflib.context_diff(text1_lines, text2_lines)
for line in diff:
    sys.stdout.write(line)

输出:

^{pr2}$

相关问题 更多 >