现有的word文件格式如下
我想转换成格式如下的JSON文件:
在网上找了相关的代码都无法实现,自己又不会更改代码,可以帮忙指点迷津改一下代码吗OVO
以下是网上找到的代码:
import docx
import re
import json
#打开docx文件
file = docx.Document("E:\Edge下载/1647846133302.docx")
list = []
val = None
#进行每段的操作
for para in file.paragraphs:
v = para.text.split()
#每行进行操作
for line in v:
items = re.compile("\.").split(line)
if (re.match('\d', line)):
if len(items) > 1:
val = {'no': items[0]}
q = ''.join([str(x) for x in items[1:]])
key = re.search('(?<=(\(|())\s*[A-D]*', q)
if key != None:
val['k'] = key.group(0).lstrip()
val['q'] = re.sub('(?<=(\(|())\s*[A-D]*\s*', ' ', q)
list.append(val)
if (re.match('A', line)):
if len(items) > 1:
val['a'] = ''.join([str(x) for x in items[1:]])
if (re.match('B', line)):
if len(items) > 1:
val['b'] = ''.join([str(x) for x in items[1:]])
if (re.match('C', line)):
if len(items) > 1:
val['c'] = ''.join([str(x) for x in items[1:]])
if (re.match('D', line)):
if len(items) > 1:
val['d'] = ''.join([str(x) for x in items[1:]])
with open('data.json', 'w') as outfile:
json.dump(list, outfile, ensure_ascii=False)
代码修改如下,供参考,其中主要是要将选项添加到一个列表即可:
import docx
import re
import json
#打开docx文件
file = docx.Document("t0323.docx")
list = []
val = None
#进行每段的操作
for para in file.paragraphs:
v = para.text.split()
#每行进行操作
s = []
for line in v:
items = re.compile("\.").split(line)
if (re.match('\d', line)):
if len(items) > 1:
val = {'no': items[0]}
q = ''.join([str(x) for x in items[1:]])
key = re.search('(?<=(\(|())\s*[A-D]*', q)
if key != None:
val['answer'] = key.group(0).lstrip()
val['title'] = re.sub('(?<=(\(|())\s*[A-D]*\s*', ' ', q)
list.append(val)
if (re.match('[ABCD]', line)):
if len(items) > 1:
s.append(''.join([str(x) for x in items[1:]]))
val['option']=s
with open('datat.json', 'w') as outfile:
json.dump(list, outfile, ensure_ascii=False)
word文档内容类似于:
1.领班属于下列哪一类管理人员(A)
A.基层管理人员 B.中层管理人员 C.高层管理人员 D.以上都不是
2.沟通、了解、激励下属的管理技能是(C)
A.技术技能 B.诊断技能 C.人际关系技能 D.分析技能
运行结果:
[{"no": "1", "answer": "A", "title": "领班属于下列哪一类管理人员( )", "option": ["基层管理人员", "中层管理人员", "高层管理人员", "以上都不是"]}, {"no": "2", "answer": "C", "title": "沟通、了解、激励下属的管理技能是( )", "option": ["技术技能", "诊断技能", "人际关系技能", "分析技能"]}]