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

2025-10-22 00:44:08

1、首先需要注慎安装python-docx

pip install python-docx

如下所示完成 python-docx的安装

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

2、读取一个word文档

首先定义一个函数

# -*- coding: 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、为了方便操作我们将结果转化为一个list 

readlist=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。
猜你喜欢