使用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 #结果以词典的形式展示:{词语:词频}
相关推荐
冯一川2 分钟前
Python 实现与 Ollama 运行的模型对话
人工智能·python
车间溜盖子7 分钟前
TE(TEC 半导体制冷片)Qc / Qh 冷热面基础定义
python
天赐范式11 分钟前
天赐范式第168天:让子代开始从父代肩膀上演化——跨代β传递demo与完整代码
python·数字生命·天赐范式·动态运行时·跨代β传递·可继承性验证·digitallife
刘天远12 分钟前
Agent系统接入编排:评分模型、状态机与Python门禁
数据库·人工智能·python
郝学胜-神的一滴12 分钟前
C++20模板元编程 04:变量模板 别名模板与模板Lambda实战
服务器·开发语言·数据结构·c++·程序人生
驭渊的小故事21 分钟前
Java 项目-jckson序列化工具
java·开发语言
君顾121 分钟前
上海24小时自助健身房系统开发实战指南:从架构设计到功能实现
java·开发语言·健身房
qq_3449205634 分钟前
Qt事件过滤器
开发语言·c++·qt
执明wa1 小时前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio