使用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 #结果以词典的形式展示:{词语:词频}
相关推荐
foundbug9997 分钟前
MATLAB实现:基于图像对比度和波段相关性的高光谱波段选择算法
开发语言·算法·matlab
2401_8844541511 分钟前
如何防止SQL触发器导致性能下降_通过精简触发器逻辑
jvm·数据库·python
m0_5967490915 分钟前
Golang如何做Clean Architecture_Golang整洁架构教程【详解】
jvm·数据库·python
czt_java18 分钟前
线程安全问题
java·开发语言·jvm
techdashen23 分钟前
Rust 模块和文件不是一回事:一次讲清 `mod`、`use`、`pub use`
开发语言·后端·rust
Wy_编程27 分钟前
go中的协程Goroutine
开发语言·golang
2401_8676239838 分钟前
如何管理应用锁_DBMS_LOCK申请自定义锁控制并发逻辑
jvm·数据库·python
basketball61641 分钟前
C++ 命名空间知识点总结:从入门到合理设计
开发语言·c++
BU摆烂会噶41 分钟前
【LangGraph】短期记忆与中断行为
人工智能·python·langchain·人机交互
WL_Aurora43 分钟前
Java多线程详解(一)
java·开发语言