Python统计中文词频的四种方法 您所在的位置:网站首页 python中英语句子怎么统计词频 Python统计中文词频的四种方法

Python统计中文词频的四种方法

2024-07-05 22:36| 来源: 网络整理| 查看: 265

统计中文词频是Python考试中常见的操作,由于考察内容较多,因此比较麻烦,那么有没有好的方法来实现呢?今天,我们总结了四种常见的中文词频统计方法,并列出代码,供大家学习参考。

中文词频统计主要是通过open()打开文本,然后read()方法读取后,采用结巴分词(jieba)模块进行分词,接着用推表推导式、Counter或者是字典的方法来统计词频,也可以采用NLTK的方法,最后格式化打印出来。

题目:统计中文文本文件【词频统计文本.txt】中长度大于1的词的词频,然后打印出词频数最高的10个词。

默认系统里已经安装好了jieba这个模块。如果还没有安装,可以在cmd下通过pip install jieba来安装这个模块。

一、字典法——常用的方法

先读取文本,然后jieba分词,再对分词后的列表进行遍历,然后用字典统计词频。这里排除了单个词,代码如下:

import jieba txt = open("词频统计文本.txt", "r").read() words = jieba.lcut(txt) counts = {} for word in words: if len(word) == 1: #排除单个字符的分词结果 continue else: counts[word] = counts.get(word,0) + 1 items = list(counts.items()) items.sort(key=lambda x:x[1], reverse=True) for i in range(10): word, count = items[i] print("{0:5}".format(word,count)) print ('已统计数量排前10的词') 二、Counter法——代码简单,速度快

先生成Counter对象,再排序,最后再打印出来。这里我们使用了most_common的方法,代码更为简洁,更好理解一点。代码如下:

import jieba from collections import Counter with open("词频统计文本.txt", "r",encoding="utf-8") as f: words = jieba.lcut(f.read()) words = [item for item in words if len(item)>1] counts = Counter(words) for word,count in counts.most_common(10): print(word,count) print ('已统计数量排前10的词') 三、NLTK方法——有点儿小麻烦

利用列表推导式筛选列表,利用NLTK中的FreqDist来统计列表中的词步,代码如下。

import jieba,os from nltk.probability import FreqDist with open("词频统计文本.txt","r",encoding="utf-8") as f: text = f.read() words = jieba.lcut(text) lst = [i for i in words if len(i)>1] freq = FreqDist(lst) for item in freq.most_common(10): word,count=item print(f"{word:


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有