项目由来

很久没更新Python高效办公系列的文章啦,最近就遇到一个很适合Python来做的一件事情,分享给大家。

是这样的,如word所示,我们需要将里面的部分数据整理为excel表格,以便我后期使用。当然,数据我做了脱敏处理,但是这些坐标都是真实存在的,是武汉的地标,这就留给大家去探索了;其次,真实的数据有很多,如果一个个拷贝就很麻烦。所以,我们就来看看Python怎么分分钟完成这项任务。

解题思路

这里的关键点是提取经纬度(X和Y),X是8位的数字,Y是7位数字,我们这时候很容易想到用正则表达式。正则表达式我之前就有讲解过,不愧是YYDS。

X是8位,很好提取,直接用d{8}就行;但是7位的Y就不能直接这样写,因为这样也会匹配到X中的数字(因为X有8位,7位小于8位,会匹配到),所以我们需要在前面和后面加上英文逗号,加以限制。

最后,要解决的就是如何读取word中的表格,和读取后怎么写入excel表中。这两个问题使用docx和xlwt库即可,别忘记安装这两个库。

pip install python-docx pip install xlwt 复制代码

实现代码

下面就是我写的代码,都加了注释,希望大家自己也尝试写一下。

from docx import Document #用于读取word import re #正则表达式库 import xlwt #写入excel的库 # 创建excel工作簿和sheet,在第一行写入表头。 workbook = xlwt.Workbook(encoding='utf-8') sheet = workbook.add_sheet('点位') sheet.write(0, 0, "点位") sheet.write(0, 1, "X") sheet.write(0, 2, "Y") # 读取word,并获取word中的第一个表 doc = Document('坐标.docx') tb1 = doc.tables[0] # 定义临时变量,用于一行行写入数据到excel。 j = 1 # 读取word表中的数据,正则表达式提取后写入excel中。 for i in range(len(tb1.rows)): if i == 0: continue title = tb1.cell(i, 0).text coordinate = tb1.cell(i, 3).text lons = re.findall('(d{8})', coordinate) lats = re.findall(',(d{7}),', coordinate) for lon, lat in zip(lons, lats): sheet.write(j, 0, title) sheet.write(j, 1, lon) sheet.write(j, 2, lat) j += 1 print(title, lons, lats) # 保存文件 workbook.save('test.xls') 复制代码