首页 技术 正文
技术 2022年11月15日
0 收藏 560 点赞 2,519 浏览 1138 个字

最近想对某些word文档(docx)的表格内容作比较, 于是找了一下相关工具. 参考Automate the Boring Stuff with Python中的word部分, 试用了python-docx – python-docx 0.8.7 documentation

演示如下. 两个简单的word文档, 各有一个表格:

读取文档中的表格到列表(为演示只对单列表格操作):

import docxdef 取表格(文件名):
文件 = docx.Document(文件名)
首个表 = 文件.tables[0]
值 = []
for 行 in 首个表.rows:
for 格 in 行.cells:
值.append(格.text)
print(文件名 + " -> " + str(值))
return 值表1 = 取表格('表1.docx')

读取结果:

表1.docx -> ['值1', '值2', '值3']

接着找到这个做比较的python库seperman/deepdiff, 来源: Get difference between two lists

from deepdiff import DeepDiff表1 = 取表格('表1.docx')
表2 = 取表格('表2.docx')print(DeepDiff(表1, 表2))

输出结果(为更可读, 已手动格式化):

{
'values_changed':
{'root[1]':
{'new_value': '值2.5', 'old_value': '值2'}
},
'iterable_item_added':
{'root[3]': '值4'}
}

显示了修改的值和添加的值, 还挺好用. 实际的表格是两列, 需要按照某个键值作对比. 于是用字典, 正好DeepDiff也提供两个字典间的比较. 双列表文件演示:

读取双列表到字典后, 进行比较:

import docx
from deepdiff import DeepDiff
from pprint import pprintdef 取表格(文件名):
文件 = docx.Document(文件名)
首个表 = 文件.tables[0]
值 = {}
for 行 in 首个表.rows:
格 = 行.cells
值[格[0].text] = 格[1].text
print(文件名 + " -> " + str(值))
return 值表1 = 取表格('双列表1.docx')
表2 = 取表格('双列表2.docx')pprint(DeepDiff(表1, 表2), indent=2)

输出如下:

{ 'dictionary_item_added': {"root['键3']"},
'values_changed': {"root['键2']": {'new_value': '值2.5', 'old_value': '值2'}}}

源码在: program-in-chinese/house_of_10000_business

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,028
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,518
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,365
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,146
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,780
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,857