Python实现自动整理表格的示例代码

Olivia ·
更新时间:2024-09-20
· 1245 次阅读

目录

前言

原理

目标实现

运行效果

前言

今天,在工作的时候,我的美女同事问我有没有办法自动生成一个这样的表格:

第一列是院校+科目,第二列是年份,第三列是数量。

这张表格是基于这一文件夹填充的,之前要一个文件夹一个文件夹打开然后手动填写年份和数量

手动整理需要耗费较长时间,于是我便开发了一个 Python 程序用来自动生成归纳表格

利用正则表达式+OS库+openpyxl生成真题年份归纳表格

原理

第一步,遍历文件夹下的所有文件和子文件夹的名称,并获取子文件夹下的文件的年份信息和数量信息

第二步,将年份信息进行格式化,连续的年份取最小值和最大值,并用“-”连接,单独的年份单独提取出,并用顿号连接

第三步,写入数据到Excel中

目标实现

遍历文件,新建数据存放的List

path=os.getcwd() file_list=list(os.walk(path)) infomation=[] yearList=[]

获取信息

 if '/' in path:   infomation.append(file_list[i][0].replace(path+'/',''))  elif '\\' in path:   infomation.append(file_list[i][0].replace(path+'\\',''))  totalNum=len(file_list[i][2])  for j in range (0,len(file_list[i][2])):   year=re.findall(r'\d{4}',file_list[i][2][j])   yearList.append(int(year[0]))  yearList.sort()

年份信息格式化

for i in range(len(yearList)):   if not res:    res.append([yearList[i]])   elif yearList[i-1]+1==yearList[i]:    res[-1].append(yearList[i])   else:    res.append([yearList[i]])  y=[]  for m in range (0,len(res)):   if(max(res[m])==min(res[m])):    y.append(str(max(res[m])))   else:    y.append(str(min(res[m]))+'-'+str(max(res[m])))  yearInfo="、".join(y)

保存数据并输出到Excel中

infomation.append(yearInfo)  infomation.append(totalNum)  print(infomation)  ws.append(infomation)  wb.save('表格.xlsx')  infomation=[]  yearList=[]

最终的完整代码如下

import os import re from openpyxl import load_workbook wb=load_workbook('表格.xlsx') ws=wb.active path=os.getcwd() file_list=list(os.walk(path)) infomation=[] yearList=[] for i in range (1,len(file_list)):  if '/' in path:   infomation.append(file_list[i][0].replace(path+'/',''))  elif '\\' in path:   infomation.append(file_list[i][0].replace(path+'\\',''))  totalNum=len(file_list[i][2])  for j in range (0,len(file_list[i][2])):   year=re.findall(r'\d{4}',file_list[i][2][j])   yearList.append(int(year[0]))  yearList.sort()  res=[]  for i in range(len(yearList)):   if not res:    res.append([yearList[i]])   elif yearList[i-1]+1==yearList[i]:    res[-1].append(yearList[i])   else:    res.append([yearList[i]])  y=[]  for m in range (0,len(res)):   if(max(res[m])==min(res[m])):    y.append(str(max(res[m])))   else:    y.append(str(min(res[m]))+'-'+str(max(res[m])))  yearInfo="、".join(y)  infomation.append(yearInfo)  infomation.append(totalNum)  print(infomation)  ws.append(infomation)  wb.save('表格.xlsx')  infomation=[]  yearList=[] 运行效果

好啦,程序不复杂,不过却大大提高了工作效率,不得不说,Python真棒!

到此这篇关于Python实现自动整理表格的示例代码的文章就介绍到这了,更多相关Python自动整理表格内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



自动 表格 示例 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号