python统计一篇文章汉字中的高频词

先处理文章,去掉空格,标点符号,及非汉字内容。

程序一:

复制代码
import re
import os
from collections import Counter


path = r"D:\stzf"
os.chdir(path)  # 修改工作路径

# 读取Word文档内容
with open('abc.txt', 'r', encoding='utf-8') as file:
    content = file.read()

# 提取所有汉字
pattern = re.compile('[\u4e00-\u9fff]+')  # 匹配所有汉字
chinese_words = pattern.findall(content)

# for i in chinese_words:
#     print(i)
#
# print('==========================================')

# 统计单个汉字的出现次数
char_counter = Counter(''.join(chinese_words))

# 统计词组的出现次数,可根据需要设定词组长度
word_counter = Counter(chinese_words)

# 输出高频出现的单个汉字
print('高频出现的单个汉字:')
for char, count in char_counter.most_common(10):  # 输出出现次数最频繁的前10个汉字
    print(char, count)

# 输出高频出现的词组
print('高频出现的词组:')
for word, count in word_counter.most_common(10):  # 输出出现次数最频繁的前10个词组
    if len(word) > 1:
        print(word, count)

程序二,使用jieba分词。

先安装jieba分词,pip install jieba --upgrade

复制代码
import os
import jieba
from collections import Counter

path = r"D:\stzf"
os.chdir(path)  # 修改工作路径
with open('ABC.txt', 'rb') as file:
    content = file.read()
# 分词并记录所有汉字
seg_list = jieba.cut(content)
chinese_words = []
for word in seg_list:
    for char in word:
        if '\u4e00' <= char <= '\u9fff':
            chinese_words.append(char)
# 统计单个汉字的出现次数
char_counter = Counter(chinese_words)
# 统计词组的出现次数,根据需要设定词组长度
word_counter = Counter([''.join(chinese_words[i:i+2]) for i in range(len(chinese_words)-1)])
# 输出高频出现的单个汉字
print('高频出现的单个汉字:')
for char, count in char_counter.most_common(200):
    print(char, count)
# 输出高频出现的词组
print('高频出现的词组:')
for word, count in word_counter.most_common(200):
    print(word, count)
相关推荐
hboot25 分钟前
AI工程师第三课 - 机器学习基础
python·scikit-learn·kaggle
顾林海5 小时前
Agent入门阶段-编程基础-Python:流程控制
python·agent·ai编程
呱呱复呱呱8 小时前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
曲幽12 小时前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码13 小时前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱1 天前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵1 天前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio1 天前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户0332126663671 天前
使用 Python 从零创建 Word 文档
python
Csvn1 天前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python