使用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 #结果以词典的形式展示:{词语:词频}
相关推荐
gugucoding几秒前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
万联WANFLOW1 小时前
多分支企业组网,IP 网段到底该怎么规划
开发语言·php
阿里嘎多学长1 小时前
2026-07-07 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Alan_6912 小时前
聊聊 Swagger/Postman/Apifox 的真实选型与 Python 项目实战
python·测试工具·postman
cookies_s_s3 小时前
C++ 字符串动态创建对象 -- 工厂模式、自动注册、模板递归动态调用
服务器·开发语言·c++
智慧物业老杨3 小时前
物业绿化数智化权责管控方案:基于工单平台的双层权限追溯模块落地实践
python
盐焗鹌鹑蛋4 小时前
【C++】继承
开发语言·c++
Metaphor6924 小时前
使用 Python 在 Word 文档中添加批注
python·word
FreakStudio4 小时前
WIZnet 开源方案分享:W55MH32 开发板 + 小智 AI实现以太网版本的小智机器人
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
栈溢出了4 小时前
Java Lambda 表达式笔记
java·开发语言·intellij-idea