统计文章词频(python实现)
来源:互联网 发布:oracle数据库实时复制 编辑:程序博客网 时间:2024/05/19 16:36
统计出文章重复词语是进行文本分析的重要一步,从词频能够概要的分析文章内容。
本文将讲述如何用python3.6版本实现英文文章词频的统计,通过本文也可以对python字典的操作有一定的认识。
实现思路:1.输入文章
2.建立用于词频计算的空字典
3.对文本的每一行计算词频
4.从字典中获取数据对到列表中
5.对列表中的数据交换位置,并排序
6.输出结果
注意事项:1.该代码只能实现英文文章的词频统计,因为中文文章分词还与其语意有关,需要用到中文分词技术
2.网上下来的英文文章可能有一些不是utf-8编码,并且文章中有一些字符包含一些格式符可能或导致解码错误(UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence)
代码实现如下:
from string import punctuation#对文本的每一行计算词频的函数def processLine(line,wordCounts): #用空格替换标点符号 line=replacePunctuations(line) words = line.split() for word in words: if word in wordCounts: wordCounts[word]+=1 else: wordCounts[word]=1def replacePunctuations(line): for ch in line : #这里直接用了string的标点符号库。将标点符号替换成空格 if ch in punctuation: line=line.replace(ch," ") return linedef main(): infile=open("englishi.txt",'r') count=10 words=[] data=[] # 建立用于计算词频的空字典 wordCounts={} for line in infile: processLine(line.lower(), wordCounts)#这里line.lower()的作用是将大写替换成小写,方便统计词频 #从字典中获取数据对 pairs = list(wordCounts.items()) #列表中的数据对交换位置,数据对排序 items = [[x,y]for (y,x)in pairs] items.sort() #因为sort()函数是从小到大排列,所以range是从最后一项开始取 for i in range(len(items) - 1, len(items) - count - 1, -1): print(items[i][1] + "\t" + str(items[i][0])) data.append(items[i][0]) words.append(items[i][1]) infile.close()if __name__ == '__main__': main()
阅读全文
1 0
- 统计文章词频(python实现)
- 如何利用python统计英文文章词频
- Python实现中文小说词频统计
- 使用Python+NLTK实现英文单词词频统计
- 使用Python+NLTK实现英文单词词频统计
- python代码简单实现一个词频统计
- python 统计词频
- python统计汉字词频
- python 统计词频
- python统计文档词频
- Python新闻联播词频统计
- python词频统计
- Python 中的词频统计
- 【python技能】词频统计
- 词频统计python
- Python进行词频统计
- 统计文章中词的词频
- Golang实现词频统计
- 导航页含小圆点
- 推荐Android开源网络请求库OkGo
- svn 使用tip
- Thinking in java 单个生产者消费者ChefWaitPerson锁获取执行程序
- 动态规划
- 统计文章词频(python实现)
- 67. Add Binary
- Python相关文章索引(9)
- CSS3-4
- mysleep
- 思维的广度与深度
- Android7.0 Activity启动流程调用栈分析
- 统计学习(五):非参数检验
- select标签 获取选中的option的value及Text内容