列表去重计数的代码
wordlist = ['你好','再见','你好','再见','你好','再见','你好','再见','你好','再见','欧了','拜拜']wordset = set(wordlist) #去掉重复内容
wordfreqs = []
for word in wordset:
freq = wordlist.count(word) #计算出现次数
wordfreqs.append((word,freq))
print(wordlist)
print(wordset)
print(wordfreqs)
运算结果:
['你好', '再见', '你好', '再见', '你好', '再见', '你好', '再见', '你好', '再见', '欧了', '拜拜']
{'欧了', '拜拜', '再见', '你好'}
[('欧了', 1), ('拜拜', 1), ('再见', 5), ('你好', 5)] 改进后的代码,用来统计斑马救援出勤记录可以用:
import pandas as pd #导入pandas库,读csv用的
pd = pd.read_csv('002.csv',encoding='gbk') #打开csv文件,读取内容
alllist = '、'.join(pd['参与人员']) #用顿号拼接人员一列
wordlist = list(alllist.split('、')) #转成列表格式,以顿号为识别分割符
print(wordlist) #打印列表格式
wordset = set(wordlist) #去掉重复内容
from openpyxl import Workbook #导入Excel模块
wb = Workbook() #创建一个Excel文件
sheet = wb.active #获取当前sheet名称
sheet.title = "第一个sheet" #修改sheet名称
sheet['A1']= "姓名" #在A1 B1单元格输入内容
sheet['B1']= "次数"
#newlist = [] #创建空列表来存储姓名和次数
for word in wordset:
freq = wordlist.count(word) #计算出现次数
sheet.append() #把内容添加到sheet
# newlist.append() #把内容加入空列表
wb.save( "测试3.xlsx") #保存到本级目录
# newlist = sorted(newlist,key=lambda k:k,reverse=True)给列表排序
#print(newlist)
13和17两行代码是把结果放入newlist列表,注释掉可正常存到Excel 第4行代码,还可以是:wordlist = alllist.split('、') 如果源文件是Excel文件的话,只需要把第二行替换成pd = pd.read_excel('result.xlsx')
页:
[1]