Python,使用 difflib 按单词比较两个句子

Mar*_*res 4 python analysis cpu-word difflib difference

我使用 difflib 并尝试比较两个句子并找出差异。

有点像这样。

https://text-compare.com/

我有这段代码,但它不是逐字分析,而是逐字分析。

import difflib

# define original text
# taken from: https://en.wikipedia.org/wiki/Internet_Information_Services
original = ["IIS 8.5 has several improvements related"]

# define modified text
edited = ["It has several improvements related"]

# initiate the Differ object
d = difflib.Differ()

# calculate the difference between the two texts
diff = d.compare(original, edited)

# output the result
print ('\n'.join(diff))
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 11

[]'s如果您从字符串中删除,并.split()在 中调用它们,.compare()也许您会得到您想要的东西。

import difflib

# define original text
# taken from: https://en.wikipedia.org/wiki/Internet_Information_Services
original = "IIS 8.5 has several improvements related"

# define modified text
edited = "It has several improvements related"

# initiate the Differ object
d = difflib.Differ()

# calculate the difference between the two texts
diff = d.compare(original.split(), edited.split())

# output the result
print ('\n'.join(diff))
Run Code Online (Sandbox Code Playgroud)

输出

+ It
- IIS
- 8.5
  has
  several
  improvements
  related
Run Code Online (Sandbox Code Playgroud)