微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python如何实现自动整理表格

这篇“Python如何实现自动整理表格”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Python如何实现自动整理表格”文章吧。

原理

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

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

第三步,写入数据到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如何实现自动整理表格”这篇文章内容,相信大家都有了一定的了解,希望小编分享内容对大家有帮助,若想了解更多相关的知识内容,请关注编程之家行业资讯频道。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐