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

统计中文词频是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:<10}{1:>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:<10}\t{count:<5}")
print ('已统计数量排前10的词')

使用这种方法,得安装nltk包,较为麻烦。

四、列表推导式法

如果不借助其它包,我们可以充分利用Python自带的count方法和列表推导式,实现词频的统计。这其中与前面排序的方法不同的是,我们采用了sorted的方法,完整代码如下:

import jieba,os
with open("词频统计文本.txt","r",encoding="utf-8") as f:
    text = f.read()
words = jieba.lcut(text)
lst = [(key,words.count(key)) for key in set(words) if len(key)>1]
items = sorted(lst,key=lambda x:x[1],reverse=True)
for i in range(10):
    word, count = items[i]
    if len(word) == 1: #排除单个字符的分词结果
        continue
    else:
        print(f"{word:<10}\t{count:<5}")
print ('已统计数量排前10的词')

五、学后反思

1. 中文词频统计主要考察文本的读取、列表的遍历、jieba分词、词频统计、排序、结果的格式化和打印输出等综合能力。因此,它是Python二级中常考的题目,认真学习,并找出多种词频统计的方法可以更好地理解Python中的相关概念和基础语法知识。

2. 四种方法中最麻烦的是NLTK法和列表推导式化,字典法和Counter方法最为常用,字典法常出现在考试中,而Counter的方法实用性更强,大家可以有选择地使用。

3. 有了词频表,后续可以进行可视化的图表生成,包括词云图和线形图等,以便更直观地观察语篇中词的特点。

### Python 实训作业示例 #### 文本词频统计与排序 对于文本处理类的任务,一个常见的实训题目是实现文本中的词频统计和排序。此任务不仅涉及字符串操作还涉及到字典的应用以及如何对数据进行有效的分析。 ```python from collections import Counter import re def word_frequency(text): words = re.findall(r'\w+', text.lower()) frequency = Counter(words) sorted_freq = dict(sorted(frequency.items(), key=lambda item: item[1], reverse=True)) return sorted_freq text_input = "This is a test. This test is only a test." print(word_frequency(text_input)) ``` 上述代码展示了如何读取一段文字并对其进行预处理,去除标点符号并将所有单词转换为小写形式以便于比较[^1]。之后利用 `collections.Counter` 来计数每个单词出现次数,并通过自定义排序函数来按频率降序排列这些项。 #### 面向对象编程实践 另一个重要的概念是在Python中应用面向对象编程(OOP),这有助于构建更复杂且易于维护的应用程序结构。 ```python class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height rect = Rectangle(5, 10) print("Rectangle Area:", rect.area()) ``` 这里创建了一个矩形(Rectangle)类作为例子说明了OOP的基本要素——属性(宽度width 和高度height)及方法(面积area)。此类可用于表示任何具有特定尺寸的矩形实体,在实际开发中有广泛用途[^2]。 #### 计算小于给定数值的所有质数 当学习到一定阶段后,可以尝试解决一些算法问题比如找出某个范围内所有的质数: ```python def find_primes_below(limit): primes = [] for candidate in range(2, limit): if all(candidate % divisor != 0 for divisor in range(2, int(candidate ** 0.5)+1)): primes.append(candidate) return primes number_limit = int(input('Enter an integer greater than 2: ')) while number_limit <= 2: number_limit = int(input('Please enter again with value more than 2: ')) primes_found = find_primes_below(number_limit) print(primes_found) ``` 这段脚本实现了获取用户输入的一个整数界限,接着遍历从2至这个上限之间的每一个候选者,检查其是否能被除它本身以外的小于等于平方根范围内的任意正整数整除;如果都不能,则认为它是质数并加入结果列表中返回[^3]。 #### 循环练习:阶乘求和 为了加深理解循环控制语句的工作原理,可以通过编写一个小项目来进行强化训练,如下所示的是计算前N个自然数对应的阶乘之和的例子。 ```python def factorial_sum(n): total = sum([factorial(x) for x in range(1, n+1)]) return total def factorial(num): product = 1 for factor in range(1, num + 1): product *= factor return product input_number = int(input('Input positive integer N to calculate the sum of first N factorials: ')) result = factorial_sum(input_number) print(result) ``` 在这个例子中,先定义辅助函数用于单独计算单个数字的阶乘值,再在外层调用该函数完成累加运算得到最终的结果输出[^4]。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PythonFun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值