我有ascii纯文本文件1(旧文件)和ascii纯文本文件2(对文件1进行了一些更改的新文件)。
在文件1和文件2之间进行比较时,python脚本中是否可以按类别列出差异,添加其他文本,删除内容和更改内容。
答案 0 :(得分:1)
我认为您需要使用difflib.Differ
来执行此操作:http://docs.python.org/2/library/difflib.html
如果你谷歌“difflib.Differ示例”,你会发现很多可以帮助你的例子。
修改强> 这是一个例子
text1 = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer
eu lacus accumsan arcu fermentum euismod. Donec pulvinar porttitor
tellus. Aliquam venenatis. Donec facilisis pharetra tortor. In nec"""
text1_lines = text1.splitlines()
text2 = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer
eu lacus accumsan arcu fermentum euismod. Donec pulvinar, porttitor
tellus. Aliquam venenatis. Donec facilisis pharetra tortor. In nec"""
text2_lines = text2.splitlines()
import difflib
d = difflib.Differ()
diff = d.compare(text1_lines, text2_lines)
print '\n'.join(diff)
结果:
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer
- eu lacus accumsan arcu fermentum euismod. Donec pulvinar porttitor
+ eu lacus accumsan arcu fermentum euismod. Donec pulvinar, porttitor
? +
- tellus. Aliquam venenatis. Donec facilisis pharetra tortor. In nec
? -
+ tellus. Aliquam venenatis. Donec facilisis pharetra tortor. In nec