如何用Python将Word文档转换为Excel表格
本文的文字及圖片來源于網(wǎng)絡(luò),僅供學(xué)習(xí)、交流使用,不具有任何商業(yè)用途,如有問題請及時(shí)聯(lián)系我們以作處理。
作者:小小明
來源:菜J學(xué)Python
Python爬蟲、數(shù)據(jù)分析、網(wǎng)站開發(fā)等案例教程視頻免費(fèi)在線觀看
https://space.bilibili.com/523606542
需求
有一個(gè)下面這種形式的word表格:
希望能轉(zhuǎn)換為下面這種格式的excel表格:
測試word文檔讀取
先測試一個(gè)word文檔前1頁的數(shù)據(jù)讀取:
from docx import Document
doc = Document("編號02 質(zhì)檢員高級技師(一級)理論試卷.docx")
for i, paragraph in enumerate(doc.paragraphs[:55]):
print(i, paragraph.text)
從讀取效果上看,各行文本數(shù)據(jù)都能很順利的獲取到。
匹配題型、題目和具體的選項(xiàng)
現(xiàn)在我們需要做的是就是匹配題型、題目和具體的選項(xiàng),觀察可以發(fā)現(xiàn)規(guī)律:
題型以大寫數(shù)字開頭
題目以普通數(shù)字+.開頭
選項(xiàng)以括號+字母開頭
?
額外需要注意的:
開頭幾行文本也存在普通數(shù)字+.開頭的,需要直接排除。
第7題的題目,和第19題的選項(xiàng)存在一些特殊的空白字符需要排除,
括號和小數(shù)點(diǎn)都同時(shí)存在半角和全角兩種情況。
?
對于需要注意的第二點(diǎn):
查看一下這2處的空白字符:
doc.paragraphs[21].text
'7.(xa0xa0)是第一家實(shí)施六西格瑪管理的公司。xa0'
doc.paragraphs[49].text
'(A)參數(shù)設(shè)計(jì) (B)常量設(shè)計(jì)u3000 (C)變量設(shè)計(jì)u3000u3000 (D)系統(tǒng)設(shè)計(jì)'
發(fā)現(xiàn)分別是xa0和u3000。
整理好大致思路,我組織一下處理代碼:
import re
from docx import Document
doc = Document("編號02 質(zhì)檢員高級技師(一級)理論試卷.docx")
black_char = re.compile("[su3000xa0]+")
chinese_nums_rule = re.compile("[一二三四]、(.+?)(")
title_rule = re.compile("d+.")
option_rule = re.compile("([ABCDEF])")
option_rule_search = re.compile("([ABCDEF])[^(]+")
# 從word文檔的“一、單項(xiàng)選擇題”開始遍歷數(shù)據(jù)
for paragraph in doc.paragraphs[5:25]:
# 去除空白字符,將全角字符轉(zhuǎn)半角字符,并給括號之間調(diào)整為中間二個(gè)空格
line = black_char.sub("", paragraph.text).replace(
"(", "(").replace(")", ")").replace(".", ".").replace("()", "( )")
# 對于空白行就直接跳過
ifnot line:
continue
if title_rule.match(line):
print("題目", line)
elif option_rule.match(line):
print("選項(xiàng)", option_rule_search.findall(line))
else:
chinese_nums_match = chinese_nums_rule.match(line)
if chinese_nums_match:
print("題型", chinese_nums_match.group(1))
從目前測試結(jié)果來看沒有問題。
保存匹配到的數(shù)據(jù)到結(jié)構(gòu)化字典
現(xiàn)在我打算將當(dāng)前匹配出來的文本數(shù)據(jù)存儲(chǔ)成字典形式的結(jié)構(gòu)化數(shù)據(jù),字典結(jié)構(gòu)的設(shè)計(jì)如下:
根據(jù)上述設(shè)計(jì)完善代碼:
import re
from docx import Document
from collections import OrderedDict
doc = Document("編號02 質(zhì)檢員高級技師(一級)理論試卷.docx")
black_char = re.compile("[su3000xa0]+")
chinese_nums_rule = re.compile("[一二三四]、(.+?)(")
title_rule = re.compile("d+.")
option_rule = re.compile("([ABCDEF])")
option_rule_search = re.compile("([ABCDEF])[^(]+")
# 保存最終的結(jié)構(gòu)化數(shù)據(jù)
question_type2data = OrderedDict()
# 從word文檔的“一、單項(xiàng)選擇題”開始遍歷數(shù)據(jù)
for paragraph in doc.paragraphs[5:]:
# 去除空白字符,將全角字符轉(zhuǎn)半角字符,并給括號之間調(diào)整為中間一個(gè)空格
line = black_char.sub("", paragraph.text).replace(
"(", "(").replace(")", ")").replace(".", ".").replace("()", "( )")
# 對于空白行就直接跳過
ifnot line:
continue
if title_rule.match(line):
options = title2options.setdefault(line, [])
elif option_rule.match(line):
options.extend(option_rule_search.findall(line))
else:
chinese_nums_match = chinese_nums_rule.match(line)
if chinese_nums_match:
question_type = chinese_nums_match.group(1)
title2options = question_type2data.setdefault(question_type, OrderedDict())
遍歷結(jié)構(gòu)化字典并存儲(chǔ)
然后我們遍歷結(jié)構(gòu)化字典,將數(shù)據(jù)保存到pandas對象中:
import pandas as pd
result = []
max_options_len = 0
for question_type, title2options in question_type2data.items():
for title, options in title2options.items():
result.append([question_type, title, *options])
options_len = len(options)
if options_len > max_options_len:
max_options_len = options_len
df = pd.DataFrame(result, columns=[
"題型", "題目"]+[f"選項(xiàng){i}"for i in range(1, max_options_len+1)])
# 題型可以簡化下,去掉選擇兩個(gè)字
df['題型'] = df['題型'].str.replace("選擇", "")
df.head()
結(jié)果:
最終保存結(jié)果:
df.to_excel("result.xlsx", index=False)
完整代碼
最終完整代碼:
import pandas as pd
import re
from docx import Document
from collections import OrderedDict
doc = Document("編號02 質(zhì)檢員高級技師(一級)理論試卷.docx")
black_char = re.compile("[su3000xa0]+")
chinese_nums_rule = re.compile("[一二三四]、(.+?)(")
title_rule = re.compile("d+.")
option_rule = re.compile("([ABCDEF])")
option_rule_search = re.compile("([ABCDEF])[^(]+")
# 保存最終的結(jié)構(gòu)化數(shù)據(jù)
question_type2data = OrderedDict()
# 從word文檔的“一、單項(xiàng)選擇題”開始遍歷數(shù)據(jù)
for paragraph in doc.paragraphs[5:]:
# 去除空白字符,將全角字符轉(zhuǎn)半角字符,并給括號之間調(diào)整為中間一個(gè)空格
line = black_char.sub("", paragraph.text).replace(
"(", "(").replace(")", ")").replace(".", ".").replace("()", "( )")
# 對于空白行就直接跳過
ifnot line:
continue
if title_rule.match(line):
options = title2options.setdefault(line, [])
elif option_rule.match(line):
options.extend(option_rule_search.findall(line))
else:
chinese_nums_match = chinese_nums_rule.match(line)
if chinese_nums_match:
question_type = chinese_nums_match.group(1)
title2options = question_type2data.setdefault(
question_type, OrderedDict())
result = []
max_options_len = 0
for question_type, title2options in question_type2data.items():
for title, options in title2options.items():
result.append([question_type, title, *options])
options_len = len(options)
if options_len > max_options_len:
max_options_len = options_len
df = pd.DataFrame(result, columns=[
"題型", "題目"]+[f"選項(xiàng){i}"for i in range(1, max_options_len+1)])
# 題型可以簡化下,去掉選擇兩個(gè)字
df['題型'] = df['題型'].str.replace("選擇", "")
df.to_excel("result.xlsx", index=False)
最終得到的文件:
總結(jié)
以上是生活随笔為你收集整理的如何用Python将Word文档转换为Excel表格的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么使用ar打包静态库
- 下一篇: Win10下小米路由器4A百兆版刷Ope