词频统计

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

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

将所有大写转换为小写

生成单词列表

生成词频统计

排序

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

输出词频最大TOP20

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

f = open('news.txt', 'r')#读取“news.txt”文件
news = f. read()

sep = ''',.?!'":'''

exclude = {'the', 'and', 'in', 'in', 'to', 'on', 'a', 'that', 'for', 't', 'of'}#去词

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

wordlist = news.lower().split()

wordDict = {}#字典

wordSet = set(wordlist) - exclude
for w in wordSet:
    wordDict[w] = wordlist.count(w)

sort_word = sorted(wordDict.items(), key=lambda x: x[1], reverse=True)#排序
for i in range(20):
    print(sort_word[i])

f = open('news_count.txt', 'a')#结果输出到文件
for i in range(20):
    f.write(str(sort_word[i])+'
')
f.close()

2.中文词频统计

下载一长篇中文文章。

从文件读取待分析文本。

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

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

pip install jieba

import jieba

list(jieba.lcut(news))

生成词频统计

排序

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

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

import jieba

f=open('s.txt', 'r', encoding="UTF-8")
str=f.read()
f.close()
new=list(jieba.cut(str))
exclude = {",", "。", "《", "》", , ":", "“", "”", "?", " ", ";", "!", "、", "
"}
sep = set(new) - exclude
dict = {}
for i in sep:
    dict[i] = new.count(i)
list = list(dict.items())
list.sort(key=lambda x:x[1], reverse=True)
f = open("null.txt", "a")
for i in range(20):
 f.write('
' + list[i][0] + " " + str(list[i][1]))
f.close()

  

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

运行结果:(由于时间关系,中文部分只选取了《三国演义》中的一部分)

('he', 50)
('was', 25)
('play', 25)
('would', 23)
('his', 17)
('dad', 17)
('i', 15)
('mandolin', 15)
('it', 11)
('could', 11)
('we', 10)
('family', 10)
('when', 9)
('had', 9)
('as', 8)
('time', 6)
('us', 6)
('not', 6)
('song', 5)
('with', 5)

原文地址:https://www.cnblogs.com/-hjd/p/8658309.html