综合练习:词频统计

综合练习

词频统计预处理

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

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

将所有大写转换为小写

生成单词列表

生成词频统计

排序

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

输出词频最大TOP20

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

f=open("file.txt","r")
news=f.read()
f.close()
sep=''',().;--'''
exclude={'the','to','and','of','in','for','on','a','when','as','not','with','that'}
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)
dictList = list(wordDict.items())
dictList.sort(key=lambda x:x[1],reverse=True)
for i in range(20):
    print(dictList[i])

2、下载一长篇中文文章。

从文件读取待分析文本。

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

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

pip install jieba

import jieba

list(jieba.lcut(news))

生成词频统计

排序

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

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

import jieba
f = open('gzccnews.txt','r',encoding = 'utf-8')
story=f.read()
f.close()
jieba.add_word('行者')
jieba.add_word('八戒')
jieba.add_word('师父')
sep=''',。‘’“”:;()!?、《》 '''
exclude={'','\n','','','','',
     '','','','','','','','','',
     '','','','','','','','','',
     '','','','','','','','','',
     '','','','','','','','','',
     '','','','','','','','','',
     '','','','','','','','','',
     '','','','',}
for c in sep:
    story = story.replace(c,'')
tem=list(jieba.cut(story))
wordDict={}
words=list(set(tem)-exclude)
for w in range(0,len(words)):
    wordDict[words[w]]=story.count(str(words[w]))
dictList = list(wordDict.items())
dictList.sort(key=lambda x:x[1],reverse=True)
f = open('Count.txt', 'a',encoding="utf-8")
for i in range(20):
    f.write(dictList[i][0] + ':' + str(dictList[i][1]) + '\n')
f.close()

原文地址:https://www.cnblogs.com/932zdb/p/8658551.html