利用python的docx模块处理word和WPS的docx格式文件

Python docx module for Word or WPS processing

本文是通过docx把word中的表格中的某些已填好的内容提取出来,存入excel表格。

首先安装docx的python模块:

pip install python-docx

由于处理的为中文和符号,改成utf-8编码格式

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from docx import Document
import pandas as pd
# 打开文件
doc = Document(ur'test_1.docx')

为了处理word中以对勾形式勾选的项目,采用下面 的方法
1、十字路口 √ 2、丁字路口 3、环形路口 4、人行立交

# 取出对号勾选的项目
print doc.tables[0].rows[3].cells[2].text
print doc.tables[0].rows[3].cells[2].text.split(u'√')[1].strip().split(' ')[0][2:]
'√' in doc.tables[0].rows[3].cells[2].text # 这个语句可以测试是否含有对勾,
# 有的话就取出对勾后面的item,否则直接返回填空的text
True
num_rows = len(doc.tables[0].rows)
print num_rows
xls = pd.read_csv(ur'output.csv')
print xls.columns[0]
diction = {}
# 找到每个excel文档中需要被记录的键值在docx文档表格中的位置
for xlskey in xls.columns:
    for row_id in range(num_rows):
        row = doc.tables[0].rows[row_id]
        for cell_id in range(len(row.cells)):
            if row.cells[cell_id].text.strip() == xlskey.strip():
                diction[xlskey] = [row_id, cell_id]
# 查看一下获得的键值位置
for key in list(diction.keys()):
    print key, diction[key]

楼层数 [21, 1]

宗地形状 [4, 1]

使用权取得时间 [14, 1]

采光通风状况 [19, 1]

已使用年限 [21, 4]

建筑朝向 [7, 1]

房屋结构 [17, 1]

交叉路口形式 [3, 1]

临街状况 [8, 1]

建筑容积率 [10, 5]

楼宇名称 [15, 5]

质量等级 [18, 1]

周围土地利用类型 [11, 1]

总建筑面积 [20, 1]

宗地位置 [0, 1]

所临道路名称 [2, 1]

装修标准 [16, 1]

那么我们认为这些表头键值对应的填入数据就在他们的右边,也就是下一个cell,因此我们只需要将row id不变,cell+1,就能取出填表内容。

# 开始填表!!!
for each_column in xls.columns:
    pos = diction[each_column]
    textion = doc.tables[0].rows[pos[0]].cells[pos[1] + 1].text
    if u'√' in textion:
        this_text = textion.strip(' ').split(u'√')[1].split()[0][2:]
    else:
        this_text = textion
    xls.loc[0, each_column] = this_text
xls
.dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; }
楼宇名称 宗地位置 所临道路名称 交叉路口形式 宗地形状 建筑朝向 临街状况 周围土地利用类型 装修标准 房屋结构 质量等级 采光通风状况 总建筑面积 楼层数 已使用年限 建筑容积率 使用权取得时间
0 百兴花园 鄂州市鄂城区凤凰路47-11号 凤凰路 丁字路口 多边形 离街 商业用地 豪华 1、钢 2、钢、钢混 3、钢混 4、混合 5、砖木 6、其它 完好 122.7平方米 8 13年

Succeed!!!

之后只需要用一个glob函数取出所有的文档的path,然后依次执行上面的命令,即可完成word表格到excel(实际上是csv形式)的自动填表过程。

2018年05月21日16:58:36

posted @ 2018-05-21 17:08  毛利小九郎  阅读(566)  评论(0编辑  收藏  举报