Difference between two Texts (Python)

Please support our Python advertiser: Programming Forums
Jun 7th, 2005
Views: 4,838
Thread Rating: 1 votes, 3.0000 average.
AddThis Social Bookmark Button
Here we apply the module difflib to compare two texts line by line and show the lines of the first text that are different from the second text.
python Syntax
  1. # find the difference between two texts
  2. # tested with Python24 vegaseat 6/2/2005
  3.  
  4. import difflib
  5.  
  6. text1 = """The World's Shortest Books:
  7. Human Rights Advances in China
  8. "My Plan to Find the Real Killers" by OJ Simpson
  9. "Strom Thurmond: Intelligent Quotes"
  10. America's Most Popular Lawyers
  11. Career Opportunities for History Majors
  12. Different Ways to Spell "Bob"
  13. Dr. Kevorkian's Collection of Motivational Speeches
  14. Spotted Owl Recipes by the EPA
  15. The Engineer's Guide to Fashion
  16. Ralph Nader's List of Pleasures
  17. """
  18.  
  19. text2 = """The World's Shortest Books:
  20. Human Rights Advances in China
  21. "My Plan to Find the Real Killers" by OJ Simpson
  22. "Strom Thurmond: Intelligent Quotes"
  23. America's Most Popular Lawyers
  24. Career Opportunities for History Majors
  25. Different Ways to Sell "Bob"
  26. Dr. Kevorkian's Collection of Motivational Speeches
  27. Spotted Owl Recipes by the EPA
  28. The Engineer's Guide to Passion
  29. Ralph Nader's List of Pleasures
  30. """
  31.  
  32. # create a list of lines in text1
  33. text1Lines = text1.splitlines(1)
  34. print "Lines of text1:"
  35. for line in text1Lines:
  36. print line,
  37.  
  38. print
  39.  
  40. # dito for text2
  41. text2Lines = text2.splitlines(1)
  42. print "Lines of text2:"
  43. for line in text2Lines:
  44. print line,
  45.  
  46. print
  47.  
  48. diffInstance = difflib.Differ()
  49. diffList = list(diffInstance.compare(text1Lines, text2Lines))
  50.  
  51. print '-'*50
  52. print "Lines different in text1 from text2:"
  53. for line in diffList:
  54. if line[0] == '-':
  55. print line,
  56.  

Only community members can submit or comment on code snippets. You must register or log in to contribute.

Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 3:52 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC