整体思路是
- 设计一个寻找题目的函数
- 先找到一个题目,在将这个题目随机插入到另一个题目之前
由于整体题目的格式还是比较单一的,所以该任务并不复杂。
涉及的知识点:insert(),re模块,正则匹配公式,docx模块
from docx import Document
import re
import random
def find(row,l):
"""
:param row: 随机生成的
:param l: 存储内容的数组
:return: 挖出的题目数组
"""
row_r = row
question =[]
if l[row_r] == None: # 避免随机到空行,由于题目格式固定,所以加1即可,其实while循环更稳妥
row_r += 1
while re.match(r'[1-9][0-9]?', l[row_r][0:2]) == None:
row_r += 1
if row_r == len(l) - 1:
row_r -= 10
question.append(l[row_r])
del l[row_r]
while re.match(r'[1-9][0-9]?', l[row_r][0:2]) == None:
question.append(l[row_r])
del l[row_r]
return question
def Myinsert(question,l):
row_i = random.randint(0, len(l))
while re.match(r'[1-9][0-9]?', l[row_i][0:2]) == None: # 找到一个题目的开始
row_i += 1
if row_i == len(l) - 1:
row_i -= 10
for i in range(len(question)):
l.insert(row_i+i,question[i])
#打开文档
document = Document(u'知识竞赛题库.docx')
#读取每段资料
l = [ paragraph.text for paragraph in document.paragraphs]
print(len(l))
for i in range(200):
row_r = random.randint(0, len(l))
re1 = find(row_r,l)
Myinsert(re1,l)
print(len(l))
document = Document() # 打开一个文档
for i in range(len(l)):
document.add_paragraph(l[i])
document.save(u'测试.docx')