码迷,mamicode.com
首页 > 其他好文 > 详细

对一个文本不同的字进行计数

时间:2018-05-28 11:41:04      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:sort   app   不同的   encoding   \n   lin   key   rip   append   

import json
fr =open(‘xyj.txt‘,‘r‘,encoding=‘utf-8‘)
characers=[]
stat={}
for line in fr:
line=line.strip()
if len(line)==0:
continue
for x in range(0,len(line)):
if line[x] in [‘ ‘,‘。‘,‘ 。‘,‘“‘,"”","{","}","(",")","[","]","<<",">>","?",",",":",":","!","?"]:
continue
if line[x] not in characers:
characers.append(line[x])
if line[x] not in stat.keys():
stat[line[x]]=0
stat[line[x]]+=1
fw1=open(‘result.json‘,‘w‘)
fw1.write(json.dumps(stat))
fw1.close()
stat=sorted(stat.items(),key=lambda d:d[1],reverse=True ) #d[1]为计数的值
print(type(stat),len(stat))

fw=open(‘xyjresult.txt‘,‘w‘,encoding="utf8")
for item11 in stat:
fw.write(item11[0]+","+str(item11[1])+"\n")
fr.close()
fw.close()

对一个文本不同的字进行计数

标签:sort   app   不同的   encoding   \n   lin   key   rip   append   

原文地址:https://www.cnblogs.com/cyh1989/p/9098729.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!