使用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 #结果以词典的形式展示:{词语:词频}
相关推荐
前端摸鱼匠3 分钟前
【AI大模型春招面试题22】层归一化(Layer Norm)与批归一化(Batch Norm)的区别?为何大模型更倾向于使用Layer Norm?
开发语言·人工智能·面试·求职招聘·batch
m0_377618235 分钟前
SQL性能调优:为何尽量使用窗口函数而非关联子查询
jvm·数据库·python
历程里程碑7 分钟前
MySQL视图:虚拟表的实战技巧
java·开发语言·数据库·c++·sql·mysql·adb
2301_796588507 分钟前
如何监控MongoDB索引碎片的产生_compact命令与碎片整理
jvm·数据库·python
lsx2024069 分钟前
Go 语言循环语句
开发语言
qq_432703669 分钟前
HTML函数运行吃CPU吗_HTML函数对处理器性能影响评估【教程】
jvm·数据库·python
逻辑驱动的ken11 分钟前
Java高频面试考点场景题10
java·开发语言·深度学习·求职招聘·春招
databook12 分钟前
如何灵活设置公式中各个部分的颜色?
python·数学·动效
曾几何时`13 分钟前
QT——对象树
开发语言·qt
埃伊蟹黄面14 分钟前
C++ —— 智能指针
开发语言·c++·算法