使用 difflib 比对 Word
- 注意,此方法比对,不包括 Word 表格中数据
方法一:
代码如下:
import docx
import codecs
from difflib import HtmlDiff
file1 = docx.Document(r'\\Mac\Home\Desktop\project\天华\test1.docx')
file2 = docx.Document(r'\\Mac\Home\Desktop\project\天华\test2.docx')
para1 = ''
para2 = ''
for para in file1.paragraphs:
para1 = para1 + para.text + '\n'
print(para1)
for para in file2.paragraphs:
para2 = para2 + para.text + '\n'
print(para2)
delta_html = HtmlDiff().make_file(para1.splitlines(), para2.splitlines())
with codecs.open(r'\\Mac\Home\Desktop\project\天华\diff.html', 'w', encoding='utf-8') as f:
f.write(delta_html)
最终生成的 HTML 文件,用浏览器打开如下:
如上图所示,差异的部分会黄色背景标出。
且两份文本并列显示,如下图:
方法二:
代码如下:
import docx
import difflib
import sys
file1 = docx.Document(r'\\Mac\Home\Desktop\project\天华\test3.docx')
file2 = docx.Document(r'\\Mac\Home\Desktop\project\天华\test4.docx')
para1 = ''
para2 = ''
for para in file1.paragraphs:
para1 = para1 + para.text + '\n'
# print(para1)
for para in file2.paragraphs:
para2 = para2 + para.text + '\n'
# print(para2)
d=difflib.Differ()
diff = difflib.ndiff(para1.splitlines(),para2.splitlines())
sys.stdout.writelines(diff)
两份源文本如下图:
比对结果如下:
这个必须点赞👍
厉害
😁
可以可以,优秀