使用Python统计txt文件中的词频

python 复制代码
# 统计词频
import jieba
jieba.load_userdict(r'\百度分词词库.txt') #载入用户自定义词典,使分词结果更准确
stops_word_path = r'\stopwords_all.txt' #载入停用词表,此处使用的是哈工大停用词表
stopwords = pd.read_table(stops_word_path,encoding='utf-8',quoting=3)['words'].tolist()
stopwords.append('\n') #在停用词中加入换行符和空格,也可以自定义其他不需要统计词频的词语
stopwords.append(' ')
# stopwords
dic = dict()
file_path = r'C:\Users\Shy0418\Desktop\text.txt' #定义要统计的txt文件路径
with open(file_path, encoding='utf-8', mode='r+') as file_read:
    lines = file_read.readlines()
    for line in lines:
        # print(list(jieba.cut(line)))
        for word in list(jieba.cut(line)):
            if word not in stopwords:
                if word in dic.keys():
                    dic[word] += 1
                else:
                    dic[word] = 1
            else:
                continue
dic
word_freq = sorted(dic.items(), key = lambda kv:(kv[1], kv[0]), reverse=True) #按词频降序排列
word_freq #结果以词典的形式展示:{词语:词频}
相关推荐
羲云网络9 小时前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc
曲径海盗11 小时前
【Python 学习第 65 天】字典基础
python·学习笔记·编程入门
Wellijohn11 小时前
Docker 瘦身、手写 MCP、异步并发:被问得最多的 12 个问题,一次答完
python·docker·mcp
VW_40414 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
yiangL_14 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
Dmz丶14 小时前
前端转 AI 100 天 Day 52:RAG 项目实战(一)——从零搭建企业知识库
python
geovindu16 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
skywalk816317 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
敲上瘾17 小时前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
卷无止境18 小时前
用 SimPy 做离散事件仿真:时钟不走步,事件自己排队
后端·python