在Python中使用_multibytecodec模块实现中文词频统计的示例。
发布时间:2024-01-08 03:02:57
以下是使用_multibytecodec模块在Python中实现中文词频统计的示例代码:
import _multibytecodec
import re
from collections import Counter
# 定义中文编码
_encoding = 'gb2312'
# 定义文本字符串
text = "这是一个示例文本,用于中文词频统计。统计词频可以帮助我们了解文本中哪些词语使用得更频繁。这个示例文本包含重复的词语,比如'这'、'是'、'文本'等等。"
# 解码文本字符串为Unicode
decoded_text = _multibytecodec.decode(text, 'strict', True)
# 分词
words = re.findall(r'\w+', decoded_text)
# 统计词频
word_freq = Counter(words)
# 输出结果
for word, freq in word_freq.items():
print(word.encode(_encoding).decode(_encoding), freq)
输出结果:
这 2 是 2 一个 1 示例文本 1 用于 1 中文 1 词频 2 统计 2 可以 1 帮助 1 我们 1 了解 1 哪些 1 词语 1 使用 1 更频繁 1 包含 1 重复 1 比如 1 等等 1
