Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, compare two sentence by words using difflib

Im using difflib and tried to compare the two sentence and get the difference.

Somewhat like this.

https://text-compare.com/

i have this code but instead of word by word it analyzed letter by letter.

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))
like image 402
Mark Anthony Libres Avatar asked Jul 18 '26 09:07

Mark Anthony Libres


1 Answers

If you remove the []'s from your strings, and call .split() on them in the .compare() perhaps you'll get what you want.

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))

Output

+ It
- IIS
- 8.5
  has
  several
  improvements
  related
like image 127
Chris Avatar answered Jul 19 '26 22:07

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!