前言
有一天朋友A向我抱怨,他的老板要求他把幾百份word填好的word表格簡(jiǎn)歷信息整理到excel中,看著他一個(gè)個(gè)將姓名,年齡……從word表格里復(fù)制粘貼到excel里,邊粘貼心里邊暗暗詛咒著自己的boss……但畢竟新手小白,又不能違背老板的意愿說我不干了,愛咋咋地,于是過來向我求助。我說,這事情好辦啊,學(xué)學(xué)python就能解決啊,簡(jiǎn)單容易上手。好了,接下來進(jìn)入正題。
思路:首先針對(duì)每一份word表格進(jìn)行分析
![](/d/20211017/891b6dea906f309f2109c95c0dc6ce54.gif)
怎么才能利用python獲取到word表格里面的信息,最初的想法是把word里面的表格轉(zhuǎn)成網(wǎng)頁格式,畢竟混跡爬蟲淺水區(qū)多年,用正則表達(dá)式處理網(wǎng)頁來獲取信息是比較輕松的,于是想到把word轉(zhuǎn)成網(wǎng)頁格式,這么一想,整個(gè)人都瘋了,幾百份文件打開然后轉(zhuǎn)成網(wǎng)頁,那也有不少勞動(dòng)量啊。于是在網(wǎng)上搜了許久,發(fā)現(xiàn)docx文件自己本身是壓縮文件,打開壓縮包之后竟然發(fā)現(xiàn)里面有個(gè)專門存儲(chǔ)word里面文本的文件。
![](/d/20211017/286a0e2825994a15b9f4090845819bed.gif)
打開文件找,發(fā)現(xiàn)我們想要的信息全都藏在這個(gè)名為document.xml的文件里
![](/d/20211017/7e7821eb6b721021cdf13fedf320543c.gif)
于是基本過程就可以確定了
1. 打開docx的壓縮包
2. 獲取word里面的正文信息
3. 利用正則表達(dá)式匹配出我們想要的信息
4. 將信息存儲(chǔ)到txt中(txt可以用excel打開)
5. 批量調(diào)用上述過程,完成一萬份簡(jiǎn)歷的提取工作
6. (檢查數(shù)據(jù)是否有錯(cuò)誤或缺失)
0x01 獲取docx信息
利用python的zipfile庫以及re庫來處理docx壓縮包里面的document.xml文件里的信息。
import zipfile
import re
def get_document(filepath):
z = zipfile.ZipFile(filepath, "r")
text = z.read("word/document.xml").decode("UTF-8")
text = re.sub(r".*?>", "", text)#去除xml里的所有標(biāo)記符
###如果多份簡(jiǎn)歷在同一個(gè)word文件里###
#table_list = text.split("XX簡(jiǎn)歷")[1:]#依據(jù)簡(jiǎn)歷標(biāo)題切分每一份簡(jiǎn)歷信息
#return table_list
return text
打印text的結(jié)果
![](/d/20211017/a97825b05d1aaf4902562e36f1ac9f64.gif)
自此,輸出了簡(jiǎn)歷中的所有相關(guān)信息
0x02 抓取各字段值
接下來根據(jù)這些相關(guān)信息抓取各個(gè)字段的值
import re
def get_field_value(text):
value_list = []
m = re.findall(r"姓 名(.*?)性 別", table)
value_list.append(m)
m = re.findall(r"性 別(.*?)學(xué) 歷", table)
value_list.append(m)
m = re.findall(r"民 族(.*?)健康狀況", table)
value_list.append(m)
'''
此處省略其他字段匹配
'''
return value_list
這樣就將每個(gè)字段匹配到的內(nèi)容以一個(gè)列表的形式返回了
0x03 將內(nèi)容寫入到文件
接下來將這個(gè)列表里的內(nèi)容寫入到txt中
str1 = ""
for value in value_list:
str1 = str1 + str(value[0]) + "\t"#每個(gè)字段值用制表符\t分隔
str1 = str1 + "\n"
with open("result.txt", "a+") as f:#將內(nèi)容以追加形式寫入到result.txt中
f.write(str1)
以上是將一個(gè)word轉(zhuǎn)成了txt
只要再對(duì)文件夾中的文件進(jìn)行批量處理就ok了
0x04 批量處理完整代碼
以下附上完整代碼
import re
import zipfile
import os
def get_document(filepath):
z = zipfile.ZipFile(filepath, "r")
text = z.read("word/document.xml").decode("UTF-8")
text = re.sub(r".*?>", "", text)#去除xml里的所有標(biāo)記符
###如果多份簡(jiǎn)歷在同一個(gè)word文件里###
table_list = text.split("XX簡(jiǎn)歷")[1:]#依據(jù)簡(jiǎn)歷標(biāo)題切分每一份簡(jiǎn)歷信息
return table_list
def get_field_value(text):
value_list = []
m = re.findall(r"姓 名(.*?)性 別", table)
value_list.append(m)
m = re.findall(r"性 別(.*?)學(xué) 歷", table)
value_list.append(m)
m = re.findall(r"民 族(.*?)健康狀況", table)
value_list.append(m)
'''
此處省略其他字段匹配
'''
return value_list
cv_list = []
for i in os.listdir(os.getcwd()):
a = os.path.splitext(os.getcwd() + "\\" + i)#獲取當(dāng)前目錄下所有文件的文件名
if a[1] == '.docx':#如果文件后綴
print(os.getcwd()+"\\"+i)
cv_list = cv_list + get_document(os.getcwd() + "\\" + i)#每份簡(jiǎn)歷信息為一個(gè)列表元素
for i in cv_list:
value_list = get_field_value(i)
str1 = ""
for value in value_list:
str1 = str1 + str(value[0]) + "\t"
str1 = str1 + "\n"
with open("result.txt", "a+") as f:
f.write(str1)
一萬份word表格簡(jiǎn)歷信息轉(zhuǎn)成了txt,然后用excel打開txt即可。
補(bǔ)充:python word表格一些操作
數(shù)據(jù)格式(datas): 列表套列表
aa =[ [1,2,3,4,5],[6,7,8,9],[]…]
import os
import requests
import json
import datetime
from docx import Document
from docx.shared import Inches, Pt, Cm
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
def create_insert_word_table(datas, stday, etday, s):
"""創(chuàng)建word表格以及插入數(shù)據(jù)"""
doc = Document()
doc.styles['Normal'].font.name = 'Calibri' # 是用來設(shè)置當(dāng)文字是西文時(shí)的字體,
doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體') # 是用來設(shè)置當(dāng)文字是中文時(shí)的字體
# doc.styles['Normal'].font.size = Pt(14) # 設(shè)置所有文字字體大小為14
distance = Inches(0.5)
sec = doc.sections[0] # sections對(duì)應(yīng)文檔中的“節(jié)”
sec.left_margin = distance # 以下依次設(shè)置左、右、上、下頁面邊距
sec.right_margin = distance
sec.top_margin = distance
sec.bottom_margin = distance
sec.page_width = Inches(11.7) # 設(shè)置頁面寬度
# sec.page_height = Inches(9) # 設(shè)置頁面高度
# doc.add_heading() # 設(shè)置標(biāo)題,但是不符合我的條件,只能試用下方p.add_run('我是文字')
p = doc.add_paragraph() # 添加段落
p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 設(shè)置中央對(duì)齊
run = p.add_run('我是文字')
run.font.size = Pt(22)
doc.add_paragraph() # 添加空段落
# 添加表格
table = doc.add_table(rows=1, cols=10, style='Table Grid')
table.style.name = 'Table Grid'
table.style.font.size = Pt(14)
table.rows[0].height = Cm(20)
title = table.rows[0].cells
title[0].text = '姓名'
title[1].text = '1'
title[2].text = '2'
title[3].text = '3'
title[4].text = '4'
title[5].text = '5'
title[6].text = '6 '
title[7].text = '7'
title[8].text = '8'
title[9].text = '9'
for i in range(len(datas)):
cels = table.add_row().cells
for j in range(len(datas[i])):
# cels[j].text = str(datas[i][j])
p = cels[j].paragraphs[0]
p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 設(shè)置中央對(duì)齊
p.add_run(str(datas[i][j]))
ph_format = p.paragraph_format
# ph_format.space_before = Pt(10) # 設(shè)置段前間距
# ph_format.space_after = Pt(12) # 設(shè)置段后間距
ph_format.line_spacing = Pt(40) # 設(shè)置行間距
doc.save('./files/項(xiàng)目總結(jié).docx')
生成示例
![](/d/20211017/2c8d32c9be5710ee582c7bf18fd3cf1e.gif)
可能出現(xiàn)的錯(cuò)誤,[Errno 13] Permission denied: ‘./files/項(xiàng)目進(jìn)展總結(jié).docx'
是因?yàn)槟愦蜷_文件未關(guān)閉,操作不了,關(guān)閉他就好了
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- 使用Python 統(tǒng)計(jì)文件夾內(nèi)所有pdf頁數(shù)的小工具
- 20行Python代碼實(shí)現(xiàn)一款永久免費(fèi)PDF編輯工具的實(shí)現(xiàn)
- 用python 制作圖片轉(zhuǎn)pdf工具
- Python開發(fā)的單詞頻率統(tǒng)計(jì)工具wordsworth使用方法
- Python快速優(yōu)雅的批量修改Word文檔樣式
- python提取word文件中的所有圖片
- 教你如何利用Python批量翻譯英文Word文檔并保留格式
- 詳解用Python把PDF轉(zhuǎn)為Word方法總結(jié)
- python 三種方法提取pdf中的圖片
- 只用40行Python代碼就能寫出pdf轉(zhuǎn)word小工具