使用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 #结果以词典的形式展示:{词语:词频}
相关推荐
于樱花森上飞舞10 小时前
【Redis】哨兵详解
java·开发语言·数据库·redis
把头塞进显示器10 小时前
电商平台-测试报告
python·selenium·pytest
ShyanZh10 小时前
【Python3基础】01-Python 环境与开发工具
python
醇氧10 小时前
Git 合并冲突与`__pycache__` 的恩怨情仇
python·numpy·fastapi
Lazionr10 小时前
二叉搜索树:从树形结构到高效查找
开发语言·c++
此生决int10 小时前
深入理解C++系列(21)——异常
开发语言·c++
乌暮10 小时前
Java 抽象类与接口详解:半成品图纸 vs 能力合同
java·开发语言·后端·学习
ShyanZh10 小时前
【Python3基础】02-输入输出与程序运行
python
乐观的Terry10 小时前
ShipDesk 完整使用教程:从新建项目到 SSH 自动发布
开发语言
伞伞悦读10 小时前
【第39期】Python 第三方包安装详解:pip、conda、requirements、版本锁定和镜像源
python·conda·pip