使用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 #结果以词典的形式展示:{词语:词频}
相关推荐
会编程的吕洞宾11 分钟前
LangChain4j 流式输出实战:让 AI 回复像打字机一样逐字显示
java·开发语言·人工智能·后端
不脱发的程序猿12 分钟前
红利ETF量化策略
人工智能·python·ai·程序员·量化交易·etf·策略回测
Apok'17 分钟前
零基础学Python量化(1):研究大纲与流程
python·机器学习·金融·数据挖掘·数据分析
鬓戈20 分钟前
llmproxy 系统开发目的和基本功能
人工智能·python
曹牧24 分钟前
JDK重定向目录
java·开发语言
郑州光合科技余经理26 分钟前
同城小程序开发:同一笔单在用户端和商家端各显示到哪
android·java·开发语言·前端·后端·uni-app·php
卷无止境37 分钟前
ARM与x86、x64的能效之争:指令集只是故事的开头
后端·python
2601_962885721 小时前
如何用 Python 计算溃疡指数(Ulcer Index)?
开发语言·python
kiracrimson1 小时前
string 容器:从 C 字符串到会自己扩容的类
开发语言·数据结构·c++·stl
benchmark_cc1 小时前
如何为 QuantDash Python SDK 编写一个最小化的连接验证脚本?
python·数据分析·pandas·量化交易·股票数据·quantdash