综合练习:词频统计

1.英文词频统

下载一首英文的歌词或文章

将所有,.?!’:等分隔符全部替换为空格

sep = ''',.!':?;'''
for c in sep:
    news = news.replace(c,' ')

  

将所有大写转换为小写

wordList = news.lower()

  

生成单词列表

wordList=news.split()

  

生成词频统计

wordDict = {}
wordSet = wordList
for w in wordSet:
   wordDict【w】=wordList.count
for w in wordDict
   print(w , wordDict[w] )

  

排序

dictList = list(wordDict.items())
dictList.sort(key= lambda x: x[1], reverse=True)

print(dictList)

  

排除语法型词汇,代词、冠词、连词

exclude = { 'the','is','so'}
wordSet = set(wordList)-exclude

  

输出词频最大TOP20

for i in range(20)
     print(dictList(i))

  

将分析对象存为utf-8编码的文件,通过文件读取的方式获得词频分析内容。

f = open("abc.txt","r",encoding='utf-8')
news = f.read()
f.close()
print(news)

  

运行结果
('i', 27)
('you', 26)
('of', 20)
('because', 18)
('to', 11)
('it', 7)
('not', 6)
('t', 6)
('my', 6)
('never', 5)

  

2.中文词频统计

下载一长篇中文文章。

从文件读取待分析文本。

news = open('gzccnews.txt','r',encoding = 'utf-8')

安装与使用jieba进行中文分词。

pip install jieba

import jieba

list(jieba.lcut(news))

生成词频统计

排序

输出词频最大TOP20(或把结果存放到文件里)

 

import jieba
f=open('wenben.txt','r',encoding='utf-8')
result = f.read()
f.close();
print(result)

  

将代码与运行结果截图发布在博客上。

 

posted on 2018-03-27 21:30  240王家乐  阅读(118)  评论(0编辑  收藏  举报