大家注意:因为微信最近又改了推送机制,经常有小伙伴说错过了之前被删的文章,比如前阵子冒着风险写的爬虫,再比如一些限时福利,错过了就是错过了。
所以建议大家加个星标,就能第一时间收到推送。👇
今天,在工作的时候,我的美女同事问我有没有办法自动生成一个这样的表格:
第一列是院校+科目,第二列是年份,第三列是数量。
这张表格是基于这一文件夹填充的,之前要一个文件夹一个文件夹打开然后手动填写年份和数量
手动整理需要耗费较长时间,于是我便开发了一个 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真棒!
交流群
时隔2个月,摸鱼学习交流群再次限时开放了。
Python技术交流群(技术交流、摸鱼、白嫖课程为主)又不定时开放了,感兴趣的朋友,可以在下方公号内回复:666,即可进入,一起 100 天计划!
老规矩,酱友们还记得么,右下角的 “在看” 点一下,如果感觉文章内容不错的话,记得分享朋友圈让更多的人知道!
【神秘礼包获取方式】
识别下方公众号,回复:1024