python比较两段文本的不同之处
python比较两段文本的不同之处,本范例预设了两段文本,程序最终可以比较出不同的行的文本输出,程序用到了difflib模块。
""" 作者:皮蛋编程(https://www.pidancode.com) 创建日期:2022/3/25 功能描述:python比较两段文本的不同之处 """ import difflib text1 = """The World's Shortest Books: Human Rights Advances in China "My Plan to Find the Real Killers" by OJ Simpson "Strom Thurmond: Intelligent Quotes" America's Most Popular Lawyers Career Opportunities for History Majors Different Ways to Spell "Bob" Dr. Kevorkian's Collection of Motivational Speeches Spotted Owl Recipes by the EPA The Engineer's Guide to Fashion Ralph Nader's List of Pleasures """ text2 = """The World's Shortest Books: Human Rights Advances in China "My Plan to Find the Real Killers" by OJ Simpson "Strom Thurmond: Intelligent Quotes" America's Most Popular Lawyers Career Opportunities for History Majors Different Ways to Sell "Bob" Dr. Kevorkian's Collection of Motivational Speeches Spotted Owl Recipes by the EPA The Engineer's Guide to Passion Ralph Nader's List of Pleasures """ # create a list of lines in text1 text1Lines = text1.splitlines(1) print("text1的行文本:") for line in text1Lines: print(line) # dito for text2 text2Lines = text2.splitlines(1) print("text2的行文本:") for line in text2Lines: print(line) diffInstance = difflib.Differ() diffList = list(diffInstance.compare(text1Lines, text2Lines)) print('-'*50) print("text1 和 text2 不同的行:") for line in diffList: if line[0] == '-': print(line)
相关文章