使用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 #结果以词典的形式展示:{词语:词频}
相关推荐
爱奥尼欧4 分钟前
【Git】远程分支删了本地还在、两个分支历史不相干?两招故障排解
开发语言·git
Java后端的Ai之路6 分钟前
Git冲突完整排查与实战:本地修改覆盖报错到成功推送全流程复盘
开发语言·人工智能·git·python·pop
skywalk81639 分钟前
AI 中台记录:使用码道基于deepseek harness制作AI数字中台9.14日
开发语言·人工智能·ai中台
CVer儿10 分钟前
vs2022配置qt
开发语言·qt
西峰u20 分钟前
Java多线程从入门到线程安全
java·开发语言·jvm
javartisan21 分钟前
AI Agent 中 Tool / Skill 的调用链路设计
python
钱栈up27 分钟前
大屏Logo定位调了8次才合格:响应式定位的经验总结安装Unsloth桌面端报PyTorch失败:Python 3.13的ABI不兼容所致
python
wuhuhuan32 分钟前
Case Generator 测试自动化平台
python·测试工具·自动化
Flynt2 小时前
Astra 自主跑了 35 小时烧掉 40 亿 token,产出为零:我给 Agent 加了三道闸
python·aigc·agent
mldong2 小时前
Python 开发者也有自己的轻量工作流引擎了:pip install 一行,5 分钟跑通一条审批流
后端·python·架构