文件方式实现完整的英文词频统计实例

可以下载一长篇的英文小说,进行词频的分析。

1.读入待分析的字符串

2.分解提取单词 

3.计数字典

4.排除语法型词汇

5.排序

6.输出TOP(20)

7.对输出结果的简要说明。

#读入待分析的字符串
fo=open('novel.txt','r')
news=fo.read()
fo.close()

#分解提取单词
news=news.lower() #字符串处理
for i in ',.':
    news=news.replace(i,'')
words=news.split(' ')  #单词的列表
#排除语法型词汇
exp={' ','the','a','and','i','to','of','in','is', 'you','he','my','me','with','it',
     'that','his','when','their','my','from','them','with','after','would','was',
     'had','that','while','all','am','only'
        'she','up','it','they','so','by','have','on','her','for','but','are','at',
     'we','this','not','has', 'will','as', 
     }
dic={}
keys=set(words)-exp  #键的集合
for w in keys:
    dic[w]= words.count(w)  #单词计数词典
#计数字典
wc=list(dic.items())   #(单词,计数)元组的列表
#列表排序
wc.sort(key=lambda x:x[1],reverse=True)  

for i in range(20): #输出前20元组
    print(wc[i])

通过分析可以知道这篇新闻主要是讲中国将降低非居民用户的天然气价格以减轻下游企业经营者的负担。

posted @ 2017-09-27 18:39  爱学习的土豆  阅读(150)  评论(0)    收藏  举报