Python中怎么将Word文档转换为Excel表格,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
测试word文档读取
先测试一个word文档前1页的数据读取:
from docx import Document
doc = Document("编号02 质检员高级技师(一级)理论试卷.docx")
for i, paragraph in enumerate(doc.paragraphs[:55]):
print(i, paragraph.text)
匹配题型、题目和具体的选项
现在我们需要做的是就是匹配题型、题目和具体的选项,观察可以发现规律:
题型以大写数字开头
题目以普通数字+.开头
选项以括号+字母开头
❝
额外需要注意的:
开头几行文本也存在普通数字+.开头的,需要直接排除。
第7题的题目,和第19题的选项存在一些特殊的空白字符需要排除,
括号和小数点都同时存在半角和全角两种情况。
❞
对于需要注意的第二点:
查看一下这2处的空白字符:
doc.paragraphs[21].text
'7.(\xa0\xa0)是第一家实施六西格玛管理的公司。\xa0'
doc.paragraphs[49].text
'(A)参数设计 (B)常量设计\u3000 (C)变量设计\u3000\u3000 (D)系统设计'
发现分别是\xa0和\u3000。
整理好大致思路,我组织一下处理代码:
import re
from docx import Document
doc = Document("编号02 质检员高级技师(一级)理论试卷.docx")
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]\)[^(]+")
# 从word文档的“一、单项选择题”开始遍历数据
for paragraph in doc.paragraphs[5:25]:
# 去除空白字符,将全角字符转半角字符,并给括号之间调整为中间二个空格
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("选项", option_rule_search.findall(line))
else:
chinese_nums_match = chinese_nums_rule.match(line)
if chinese_nums_match:
print("题型", chinese_nums_match.group(1))
保存匹配到的数据到结构化字典
现在我打算将当前匹配出来的文本数据存储成字典形式的结构化数据,字典结构的设计如下:
根据上述设计完善代码:
import re
from docx import Document
from collections import OrderedDict
doc = Document("编号02 质检员高级技师(一级)理论试卷.docx")
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]\)[^(]+")
# 保存最终的结构化数据
question_type2data = OrderedDict()
# 从word文档的“一、单项选择题”开始遍历数据
for paragraph in doc.paragraphs[5:]:
# 去除空白字符,将全角字符转半角字符,并给括号之间调整为中间一个空格
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())
然后我们遍历结构化字典,将数据保存到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"选项{i}"for i in range(1, max_options_len+1)])
# 题型可以简化下,去掉选择两个字
df['题型'] = df['题型'].str.replace("选择", "")
df.head()
结果:
最终保存结果:
df.to_excel("result.xlsx", index=False)
最终完整代码:
import pandas as pd
import re
from docx import Document
from collections import OrderedDict
doc = Document("编号02 质检员高级技师(一级)理论试卷.docx")
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]\)[^(]+")
# 保存最终的结构化数据
question_type2data = OrderedDict()
# 从word文档的“一、单项选择题”开始遍历数据
for paragraph in doc.paragraphs[5:]:
# 去除空白字符,将全角字符转半角字符,并给括号之间调整为中间一个空格
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"选项{i}"for i in range(1, max_options_len+1)])
# 题型可以简化下,去掉选择两个字
df['题型'] = df['题型'].str.replace("选择", "")
df.to_excel("result.xlsx", index=False)
最终得到的文件:
关于Python中怎么将Word文档转换为Excel表格问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4848094/blog/4909218