Python批量提取Word中表格内容,⼀键写⼊Excel
Hello,我是⼩张,⼤家好久不见~
今天⽂章介绍⼀个实战案例,与⾃动化办公相关;案例思想是源于前两天帮读者做了⼀个 demo ,需求⼤致将⼀上百个 word 中表格内容提取出来(所有word 中表格样式⼀样),把提取到的内容⾃动存⼊ Excel 中
word 中表格形式如下
⽬前含有数个上⾯形式的 word ⽂档需要整理,⽬标是利⽤ python ⾃动⽣成下⾯形式 excel 表格
正式案例讲解之前,先看⼀下转换效果,脚本先把指定⽂件夹下的 doc ⽂件转化为 docx ,随后⾃动⽣成⼀个 excel 表格,表格内中即为所有 word 中的内容
涉及的库
本案例中⽤到的 Python 库有以下⼏个
python-docx
pandas
os
pywin32
doc 转化为 docx
本案例中 word 中表格内容的提取⽤到的是 python-docx 库,关于 python-docx ⼀些基础⽤法可以参考
word ⽂档有时是以 doc 类型保存的, python-docx 只能处理 docx ⽂件类型,在提取表格内容之前,需进⾏⼀次⽂件类型格式转换:把 doc 批量转化为docx;
doc 转 docx 最简单的⽅式通过Office 中 word 组件打开 doc ⽂件,然后⼿动保存为 docx ⽂件,对于单个⽂档这个⽅法还⾏,⽂档数量达到上百个的话还⽤这种⽅法就有点烦了,
这⾥介绍⼀个 python 库 pywin32 来帮助我们解决这个问题,pywin32 作为扩展模块,⾥⾯封装了⼤量 Windows API 函数,例如调⽤ Office 等应⽤组件、删除指定⽂件、获取⿏标坐标等等
利⽤ pywin32 控制Office 中 Word 组件⾃动完成打开、保存操作,把所有 doc ⽂件类型转化为 docx ⽂件类型,步骤分为以下三步:
1,建⽴⼀个 word 组件
from win32com import client as wc
word = wc.Dispatch('Word.Application')
2,打开 word ⽂件
doc = word.Documents.Open(path)
3,保存关闭
doc.SaveAs(save_path,12, False, "", True, "", False, False, False, False)
doc.Close()
完整代码
path_list = os.listdir(path)
doc_list = [os.path.join(path,str(i)) for i in path_list if str(i).endswith('doc')]
word = wc.Dispatch('Word.Application')
print(doc_list)
for path in doc_list:
print(path)
save_path = str(path).replace('doc','docx')
doc = word.Documents.Open(path)
doc.SaveAs(save_path,12, False, "", True, "", False, False, False, False)
doc.Close()
print('{} Save sucessfully '.format(save_path))
word.Quit()
docx 库提取单个表格内容
在批量操作之前,⾸先需要搞定单个表格中的内容,只要我们搞定了单个 word,剩下的加⼀个递归即可
⽤ docx 库对 word 中表格内容提取,主要⽤到 Table、rows、cells 等对象
Table 表⽰表格,rows 表⽰表格中⾏列表,以迭代器形式存在;cells 表⽰单元格列表,也是以迭代器形式
操作之前,需了解下⾯⼏个基础函数
通过 Document 函数读取⽂件路径,返回⼀个 Document 对象
Document.tables 可返回 word 中的表格列表;
< 返回该单元格中⽂本信息
了解了上⾯内容之后,接下来的操作思路就⽐较清晰了;word 表格中⽂本信息可以通过两个 for 循环来完成:第⼀个 for 循环获取表格中所有⾏对象,第⼆个 for 循环定位每⼀⾏的单元格,借助 获取单元格⽂本内容;
⽤代码试⼀下这个思路是否可⾏
document = docx.Document(doc_path)
for table in document.tables:
for row_index,row in ws):
for col_index,cell in lls):
print(' pos index is ({},{})'.format(row_index,col_index))
print('cell text is {}'.))
会发现,最终提取到的内容是有重复的,,,
出现上⾯原因,是由于单元格合并问题,例如下⾯表格的单元格是合并了(1,1)->(1,5),docx 库在处理这类合并单元格时并没有当成⼀个,⽽是以单个形式进⾏处理,因此 for 迭代时(1,1)->(1,5)单元格返回了五个,每⼀个单元格⽂本信息都返回是
⾯对以上⽂本重复问题,需要添加⼀个去重机制,姓名、性别、年龄...学历学位等字段作为列名 col_keys,后⾯王五、⼥、37、... 学⼠等作为col_values,提取时设定⼀个索引,偶数为 col_keys, 奇数为 col_vaues ;
代码重构后如下:
document = docx.Document(doc_path)
col_keys = [] # 获取列名
col_values = [] # 获取列值
index_num = 0
# 添加⼀个去重机制
fore_str = ''
for table in document.tables:
for row_index,row in ws):
for col_index,cell in lls):
if fore_str != :
if index_num % 2==0:
col_keys.)
else:
col_values.)
fore_str =
index_num +=1
print(f'col keys is {col_keys}')
print(f'col values is {col_values}')
最终提取后的效果如下
批量 word 提取,保存⾄ csv ⽂件中
能够处理单个 word ⽂件之后,⼀个递归即可提取到所有 word ⽂本表格内容,最后利⽤ pandas 把获取到的数据写⼊到 csv ⽂件即可!
python怎么读取py文件
def GetData_frompath(doc_path):
document = docx.Document(doc_path)
col_keys = [] # 获取列名
col_values = [] # 获取列值
index_num = 0
# 添加⼀个去重机制
fore_str = ''
for table in document.tables:
for row_index,row in ws):
for col_index,cell in lls):
if fore_str != :
if index_num % 2==0:
col_keys.)
else:
col_values.)
fore_str =
index_num +=1
return col_keys,col_values
pd_data = []
for index,single_path in enumerate(wordlist_path):
col_names,col_values = GetData_frompath(single_path)
if index == 0:
pd_data.append(col_names)
pd_data.append(col_values)
else:
pd_data.append(col_values)
df = pd.DataFrame(pd_data)
<_csv(word_paths+'/result.csv', encoding='utf_8_sig',index=False)
证件号、⾝份证号格式
打开⽣成的 csv ⽂件会发现联系⽅式、⾝份证号两栏的数字格式是以数值存储,不是我们想要的类型,想要完整展⽰,需存储之前把数值转化为⽂本
解决⽅法,到所在的单元格,前⾯元素前⾯加⼀个 ’\t‘ 制表符即可
col_values[7] = '\t'+col_values[7]
col_values[8] = '\t'+col_values[8]
源码获取
本案例中⽤到的源码数据获取⽅式,关注公号:⼩张Python,在公号后台回复关键字:210328 即可!
⼩结
本案例中只⽤到了 docx 库中的⼀部分⽅法,主要涉及到了 word 中 Table 的基本操作,对于⼀些从事⽂职⼯作的同学来说⽇常⼯作中可能会遇到上⾯相
似问题,因此特意分享在这⾥,希望能够对⼤家有所帮助
好了,以上就是本篇⽂章的全部内容了,最后感谢⼤家的阅读,我们下期见!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。