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

综合练习:词频统计

时间:2018-03-27 18:43:43      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:close   with   print   文件夹   utf-8   odi   coding   排除   sorted   

#读取英文歌词文件
file=open(‘dd.txt‘,‘r‘,encoding=‘utf-8‘)
word=file.read()
file.close()
#排除符号
di=‘‘‘.,‘‘""?!:;‘‘‘
for i in di:
    word=word.replace(i,‘‘)
#大写转换小写 空格分割
word=word.lower().split()
#定义字典存放数据
diet={}
for c in word:
    count=word.count(c)
    diet[c]=count
for c in diet:
    print(diet[c],c)
#排除介词等无关词语
de={‘the‘,‘and‘,‘i‘,‘in‘,‘to‘,‘in‘,‘with‘,‘it‘}
for i in de:
    diet.pop(i)
#排序
count = sorted(diet.items(),key=lambda items: items[1], reverse=True)
#将结果存放在文件夹
f=open("F:text.txt",‘w‘)
for i in range(20):
    f.write(count[i][0]+" "+str(count[i][1] )+‘\n‘)
f.close()

 

综合练习:词频统计

标签:close   with   print   文件夹   utf-8   odi   coding   排除   sorted   

原文地址:https://www.cnblogs.com/zzl-0402/p/8658718.html

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