这里要处理的问题:
收到了好多读书心得的投稿,需要统计其中的学生信息,包括姓名,学号,班级等等
(如果你也有这种工作,建议使用问卷统计信息和问卷附件提交文件的形式来做这个活动,会更加简单省事,我这也是没办法了,只能自己再处理了)
处理步骤:
1. 获取文件夹下所有docx 文件的文件名
2. 读取docx 文件中表格的文本
3. 创建 xls文件把需要的信息保存到文件中
代码:
- from docx import Document
- import xlwt
- import os
- #获取文件夹下的所有 docx 后缀的文件名
- file_dir = '/Users/thrive/Downloads'
- #得到包含所有文件名的变量
- filenametemp=[]
- for parent, dirnames, filenames in os.walk(file_dir):
- filenametemp.append(filenames)
- #获取后缀是 docx 的文件名
- filename=[]
- for file in filenametemp[0]:
- if str(file).endswith('docx'):
- filename.append(file)
- print(len(filename))#看一下一共获取了多少个文件
- print(filename[0])#看一下变量中的第一个文件名
-
输出看一下:有 92 个文件,变量中的第一个文件名是 xxx
- #创建一个 excel 文件写入想要的信息
- workbook = xlwt.Workbook(encoding='utf-8')
- sheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True)#给excel文件添加sheet
- n=0 #初始化要加入到表格的行
- #逐个读取文件开始操作
- for file in filename:
- doc = Document('/Users/thrive/Downloads/'+file)
- tbs = doc.tables#获取全部表格
- if len(tbs)==0:#有的文件格式不正确,读取不到表格,找到他们
- print(file)
- else:#对格式正确的文件进行处理
- # method 1
- text1=[]
- table = tbs[0]#第一个表格就是我们要的
- #按行获取文本内容
- row_num = len(table.rows)
- for i in range(row_num):
- rowtemp=table.rows[i]
- row_string = [cell.text for cell in rowtemp.cells]
- text1.append(row_string)
- # save into xlsx
- sheet1.write(n,0,text1[0][1])#name
- sheet1.write(n,1,text1[1][1])#class
- sheet1.write(n,2,text1[0][5])#student number
- sheet1.write(n,3,text1[1][5])#college 1
- sheet1.write(n,4,text1[1][3])#college 2
- sheet1.write(n,5,text1[3][1])#book name
- n=n+1
-
- workbook.save('test.xls')
-
输出结果: xls 文件
另外显示有五个人的文件里边是没有表格的,没有按规定提交
到这已经可以了,多说一点,对于 docx 中表格内容的读取还可以这样操作:
- # method 2
- text2=[]
- for tb in tbs:
- for row in tb.rows:
- for cell in row.cells:
- text2.append(cell.text)
- print(text2[0])
-
结果:
祝你工作顺利,学业进步