使用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 #结果以词典的形式展示:{词语:词频}
相关推荐
starzy19908 小时前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
M--Y8 小时前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
岁月宁静9 小时前
DeepSeek Harness 实战与架构解析:让 Agent 从“会聊”到“能交付”
人工智能·python·agent
LiaoWL1239 小时前
NumPy 入门实战(二):向量化与余弦相似度——从 ndarray 到 Embedding
python·numpy·embedding
forest_099 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
吴可可1239 小时前
WScript Shell操作注册表详解
开发语言
纪念 22910 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
databook12 小时前
时间序列数据,先拆规律还是先查异常
python·数据挖掘·数据分析
师夷长技以自愈13 小时前
手搓 AI Agent 第 8 篇:从手写循环到画流程图——LangGraph 封装
人工智能·python
aifannihao14 小时前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib