Python词频统计

在Python中进行词频统计是一项基础的文本分析任务,通常涉及以下步骤:

  1. 文本预处理:包括去除标点符号、转换为小写、去除停用词等。
  2. 分词:将文本分割成单词或词汇。
  3. 统计词频:对分词后的结果进行计数。

以下是一个简单的Python脚本,使用collections模块中的Counter类来统计词频:

复制代码
import re
from collections import Counter

# 示例文本
text = "This is a sample sentence. This sentence is really just a sample."

# 文本预处理:去除标点符号并转换为小写
cleaned_text = re.sub(r'[^\w\s]', '', text).lower()

# 分词
words = cleaned_text.split()

# 统计词频
word_counts = Counter(words)

# 输出词频统计结果
print(word_counts)

# 如果需要按照词频排序
most_common_words = word_counts.most_common()
print(most_common_words)

在这个脚本中,我们首先使用正则表达式re.sub(r'[^\w\s]', '', text)来移除文本中的标点符号,然后使用lower()方法将所有文本转换为小写,以保证词频统计时不区分大小写。

split()方法用于将文本分割成单词列表,然后我们使用Counter来统计每个单词出现的次数。

Counter.most_common()方法可以返回一个包含单词及其对应频率的列表,按照频率从高到低排序。

如果你需要更复杂的文本处理,比如去除停用词(stop words),可以使用nltk库中的stopwords集合:

复制代码
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

nltk.download('punkt')
nltk.download('stopwords')

# 示例文本
text = "This is a sample sentence. This sentence is really just a sample."

# 文本预处理:去除标点符号、转换为小写,并分词
tokens = word_tokenize(text)
cleaned_tokens = [word.lower() for word in tokens if word.isalpha()]

# 去除停用词
stop_words = set(stopwords.words('english'))
filtered_tokens = [word for word in cleaned_tokens if word not in stop_words]

# 统计词频
word_counts = Counter(filtered_tokens)

# 输出词频统计结果
print(word_counts)
print(word_counts.most_common())

在这个例子中,我们首先使用nltk库的word_tokenize函数进行分词,然后去除停用词,并再次使用Counter进行词频统计。使用nltk.download('punkt')nltk.download('stopwords')确保我们已经下载了所需的分词和停用词数据集。

相关推荐
源代码•宸几秒前
Golang语法进阶(定时器)
开发语言·经验分享·后端·算法·golang·timer·ticker
水中加点糖1 分钟前
RagFlow实现多模态搜索(文、图、视频)与(关键字/相似度)搜索原理(二)
python·ai·音视频·knn·ragflow·多模态搜索·相似度搜索
期待のcode2 分钟前
TransactionManager
java·开发语言·spring boot
郝学胜-神的一滴3 分钟前
Linux系统编程:深入理解读写锁的原理与应用
linux·服务器·开发语言·c++·程序人生
贾宝玉的玉宝贾3 分钟前
FreeSWITCH 简单图形化界面52 - 拨号应用 Answer 介绍
python·django·voip·freeswitch·sip·ippbx·jssip
Larry_Yanan3 分钟前
Qt多进程(十一)Linux下socket通信
linux·开发语言·c++·qt
Hello.Reader4 分钟前
PyFlink JAR、Python 包、requirements、虚拟环境、模型文件,远程集群怎么一次搞定?
java·python·jar
代码游侠12 分钟前
学习笔记——ESP8266 WiFi模块
服务器·c语言·开发语言·数据结构·算法
0和1的舞者13 分钟前
Python 中四种核心数据结构的用途和嵌套逻辑
数据结构·python·学习·知识
weixin_4624462314 分钟前
Python 使用 PyQt5 + Pandas 实现 Excel(xlsx)批量合并工具(带图形界面)
python·qt·pandas