盤(pán)點(diǎn)一個(gè)Python自動(dòng)化辦公的實(shí)戰(zhàn)案例(word文件處理)
回復(fù)“書(shū)籍”即可獲贈(zèng)Python從入門(mén)到進(jìn)階共10本電子書(shū)
大家好,我是Python進(jìn)階者。
一、前言
前幾天在Python鉑金交流群【Jethro Shen】問(wèn)了一個(gè)Python自動(dòng)化辦公的問(wèn)題,提問(wèn)截圖如下:

代碼運(yùn)行后的結(jié)果:

他預(yù)期的效果是選項(xiàng)和答案部分也需要顯示出來(lái),目前看上去還是沒(méi)有顯示出來(lái)。

他的原始代碼如下:
import re
black_char = re.compile("[\s\u3000\xa0]+")
chinese_nums_rule = re.compile("[一二三四]、(.+?)\(")
title_rule = re.compile("\d+.")
option_rule = re.compile("\([ABCDEF]\)")
option_rule_search = re.compile("\([ABCDEF]\)[^(]+")
answer_rule = re.compile("\([ABCDEF]\)")
# 從word文檔的“一、單項(xiàng)選擇題”開(kāi)始遍歷數(shù)據(jù)
for paragraph in doc.paragraphs[1:100]:
# 去除空白字符,將全角字符轉(zhuǎn)半角字符,并給括號(hào)之間調(diào)整為中間二個(gè)空格
line = black_char.sub("", paragraph.text).replace(
"(", "(").replace(")", ")").replace(".", ".").replace("()", "( )").replace("【", "").replace("】", "")
# 對(duì)于空白行就直接跳過(guò)
if not line:
continue
if title_rule.search(line):
print("題目", line)
elif option_rule.search(line):
print("選項(xiàng)", option_rule_search.findall(line))
elif answer_rule.search(line):
print("答案",answer_rule.findall(line))
else:
chinese_nums_match = chinese_nums_rule.search(line)
if chinese_nums_match:
print("題目", chinese_nums_match.group(1))
二、實(shí)現(xiàn)過(guò)程
這里【瑜亮老師】指出是正則表達(dá)式的問(wèn)題,沒(méi)匹配到,自然就出不來(lái)結(jié)果。后來(lái)【不上班能干啥!】給了一份代碼,如下所示:
import re
black_char = re.compile("[\s\u3000\xa0]+")
chinese_nums_rule = re.compile("[一二三四]、(.+?)\(")
title_rule = re.compile("\d+.")
option_rule = re.compile("([A-F]\..+?)\s")
# option_rule_search = re.compile("\([A-F]\)[^(]+")
answer_rule = re.compile("【答案】([A-F])")
# 從word文檔的“一、單項(xiàng)選擇題”開(kāi)始遍歷數(shù)據(jù)
for paragraph in doc.paragraphs[1:100]:
# 去除空白字符,將全角字符轉(zhuǎn)半角字符,并給括號(hào)之間調(diào)整為中間二個(gè)空格
line = black_char.sub(" ", paragraph.text).replace(
"(", "(").replace(")", ")").replace(".", ".").replace("()", "( )") + " "
# 對(duì)于空白行就直接跳過(guò)
if not line:
continue
if title_rule.match(line):
print("題目", line)
elif option_rule.match(line):
print("選項(xiàng)", option_rule.findall(line))
if '【答案】' in line and answer_rule.search(line):
print("答案",answer_rule.findall(line))
elif answer_rule.match(line):
print("答案",answer_rule.findall(line))
else:
chinese_nums_match = chinese_nums_rule.match(line)
if chinese_nums_match:
print("題目", chinese_nums_match.group(1))
運(yùn)行之后,可以得到預(yù)期發(fā)效果:

歸根結(jié)底,還是正則表達(dá)式的問(wèn)題。
后來(lái)【甯同學(xué)】使用 openpyxl庫(kù),也給了一份代碼,如下所示:
from docx import Document
import openpyxl
wb = openpyxl.Workbook()
ws = wb.active
ws.append(['題目','選項(xiàng)1','選項(xiàng)2','選項(xiàng)3','選項(xiàng)4','答案'])
doc = Document("題庫(kù).docx")
all_runs = doc.paragraphs
rows = []
for run in all_runs[1:]:
print([run.text])
if '【答案】' in run.text:
text_list= run.text.replace('\n ','\t\t').replace('【答案】','').split('\t\t')
rows += text_list
ws.append(rows)
rows = []
continue
text_list= run.text.replace('\n ','\t\t').split('\t\t')
rows += text_list
wb.save('1.xlsx')
可以得到預(yù)期的效果,如下圖所示:
效果還是不錯(cuò)的!

后來(lái)【不上班能干啥!】還結(jié)合Pandas給了一份代碼,如下所示:
import re
import pandas as pd
from docx import Document
doc = Document("題庫(kù).docx")
text = re.sub(r'<.*?>', '', doc.part.blob.decode('utf-8'), flags=re.S)
a = pd.DataFrame(re.findall(r'(\d+\..*?)(A\..*?)(B\..*?)(C\..*?)(D\..*?)【答案】([A-Z])', text),
columns=['題目', '選項(xiàng)一', '選項(xiàng)二', '選項(xiàng)三', '選項(xiàng)四', '答案'])
a.replace([r'^\s+', '\s+$'], '', regex=True, inplace=True)
a.to_excel('題庫(kù).xlsx', index=False)
這個(gè)Pandas功力已經(jīng)到爐火純青的地步了!

三、總結(jié)
大家好,我是皮皮。這篇文章主要盤(pán)點(diǎn)了一個(gè)Python自動(dòng)化辦公的問(wèn)題,文中針對(duì)該問(wèn)題,給出了具體的解析和代碼實(shí)現(xiàn),幫助粉絲順利解決了問(wèn)題。
最后感謝粉絲【W(wǎng)YM】提問(wèn),感謝【dcpeng】、【瑜亮老師】、【不上班能干啥!】、【甯同學(xué)】給出的思路和代碼解析,感謝【水方人子】、【D I Y】、【冫馬讠成】、【貓藥師Kelly】等人參與學(xué)習(xí)交流。
大家在學(xué)習(xí)過(guò)程中如果有遇到問(wèn)題,歡迎隨時(shí)聯(lián)系我解決(我的微信:pdcfighting),應(yīng)粉絲要求,我創(chuàng)建了一些高質(zhì)量的Python付費(fèi)學(xué)習(xí)交流群和付費(fèi)接單群,歡迎大家加入我的Python學(xué)習(xí)交流群和接單群!

小伙伴們,快快用實(shí)踐一下吧!如果在學(xué)習(xí)過(guò)程中,有遇到任何問(wèn)題,歡迎加我好友,我拉你進(jìn)Python學(xué)習(xí)交流群共同探討學(xué)習(xí)。
------------------- End -------------------
往期精彩文章推薦:

歡迎大家點(diǎn)贊,留言,轉(zhuǎn)發(fā),轉(zhuǎn)載,感謝大家的相伴與支持
想加入Python學(xué)習(xí)群請(qǐng)?jiān)诤笈_(tái)回復(fù)【入群】
萬(wàn)水千山總是情,點(diǎn)個(gè)【在看】行不行
/今日留言主題/
隨便說(shuō)一兩句吧~~
