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

综合练习:词频统计

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

标签:分享   sort   highlight   技术   tle   gpo   item   rds   image   

f = open(‘test.txt‘,‘r‘)
news = f.read()
f.close()

sep = ‘‘‘.,‘?!:"‘‘‘
exclude = {‘the‘,‘and‘,‘to‘,‘a‘,‘of‘,‘was‘,‘on‘,‘with‘,‘i‘,‘s‘,‘is‘,‘were‘,‘that‘,‘back‘,‘at‘,‘little‘,‘have‘}
for w in sep:
    news = news.replace(w,‘ ‘)

wordList = news.lower().split()
wordDict = {}
‘‘‘
for v in wordList:
    wordDict[v] = wordDict.get(v, 0)+1
for v in exclude
    del( wordDict[v])
‘‘‘

wordset = set(wordList) - exclude
for v in wordset:
    wordDict[v] = wordList.count(v)

dictList = list(wordDict.items())
dictList.sort(key=lambda x:x[1],reverse=True)
for i in range(20):
    print(dictList[i])

f = open(‘newscount.txt‘,‘a‘)
for i in range(25):
    f.write(dictList[i][0]+‘ ‘+str(dictList[i][1])+‘\n‘)

运行结果:

 

 

技术分享图片

综合练习:词频统计

标签:分享   sort   highlight   技术   tle   gpo   item   rds   image   

原文地址:https://www.cnblogs.com/cgq520/p/8658573.html

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