python-docx读取docx文档内容非常方便,按下面代码就能顺利读取段落文本:
doc = docx.Document(root_url) # == 打开文件,root_url为docx文档的物理路径
forparagraph indoc.paragraphs: # == 按段读取
str_content = paragraph.text # == 文本内容
上面代码是把整段文本读取出来,如何读取指定样式的文本并替换为需要的内容呢?比如下面的需求:
填空题
He is going to leave for Beijing.
The film starts at 7:00 on Monday evening.
It is difficult for old people to speak English.
The girls often listen to music at home.Jim sits in front ofme, and I sit behind him.
这是一个题库导入的填空题的模板,要求把下划线的内容替换为填空的序号,如:(1),(2),(3)等,带下划线的字符为标准答案,存在题库中。
通常思路是把读取段落内容采用替换的字符的方法来解决,但是如果一段中出现多个相同字符或字符是一个单词中的一部份就有问题了。因此,必须采用精确的定位方法来实现,下面就是实现方法:
forparagraph indoc.paragraphs: # == 按段读取
forstyle inparagraph.runs: # == 读取格式
ifstyle.underline:
underline_text.append(style.text) # == 读取格式文本
str_content+=" ( "+str(i_style+1)+" ) "
i_style += 1
else:
str_content += style.text
输出结果:
解决问题!
谢谢关注!
3710

被折叠的 条评论
为什么被折叠?



