Python实现word选择题自动选择答案上

2025-04-27 05:27:36

1、首先需要安装python-docxpip install python-docx如下所示完成python-docx的安装

Python实现word选择题自动选择答案上

2、读取一个word文档首先定义一个函数# -*- codi艘绒庳焰ng: UTF-8 -*import docxdef readDocx烫喇霰嘴(docName): #该函数返回一个字符串 fullText = [] doc = docx.Document(docName) paras = doc.paragraphs for p in paras: fullText.append(p.text) return '\n'.join(fullText)该函数读取指定文档返回一个字符串unicode

Python实现word选择题自动选择答案上

3、使用步骤2中定义的函数,进行word文档的操作,strword=readDocx('E:\software\demo.docx')print(strword)这里将把demo.docx这个word文档的文字读取输出

Python实现word选择题自动选择答案上
Python实现word选择题自动选择答案上
Python实现word选择题自动选择答案上

4、为了方便操作我们将结果转化为一个listreadlist=list(strword)这样就把strword转化为list属性的值

Python实现word选择题自动选择答案上
Python实现word选择题自动选择答案上

5、接下来把'()'的位置找出来,然后在里面插入需要选择的答案然後,得到要插入的位置,将它保存到一个 list中把这些位置保存在一个列表中zjl=[]for i ,val in enumerate(readlist): if val == ')' or val == ')': zjl.append(i)print(zjl)这个时候没成功输出竟然报错UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal if val == ')' or val==')':解决这个问题的办法是开头加入这个代码:import sysreload(sys)sys.setdefaultencoding('utf8')设置编码为utf-8这样我们就能成功取到位置了,如下所示:

Python实现word选择题自动选择答案上
Python实现word选择题自动选择答案上
Python实现word选择题自动选择答案上

6、取到位置我们就可以在指定位置传入需要的元素了zjl=[]for i ,val in enumerate(readlist): if val == ')媪青怍牙' or val==')': zjl.append(i)for i in range(len(zjl)): readlist.insert(zjl[i]+i,'A')print(readlist)如下图即可插入A到括号里

Python实现word选择题自动选择答案上
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢