使用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 #结果以词典的形式展示:{词语:词频}
相关推荐
huisheng_qaq24 分钟前
【Python基础篇-04】深入理解python的函数、参数与作用域
python·ai·函数·参数作用域
宸津-代码粉碎机5 小时前
OpenAI 连夜迎战 Grok Bot 和 Muse:AI 智能体从 “会聊天” 到 “能办事”,现在入场还来得及吗
java·大数据·人工智能·分布式·python
Y3815326625 小时前
SERP API 计费口径:credits_charged、执行失败扣费与退款边界
python·搜索引擎
chenbingjie_c6 小时前
C++ 进阶核心知识点总结:模板、内存分区、new/delete、内存池
开发语言·c++
Escalating_xu7 小时前
【C 语言】深入理解指针(1·下):指针运算、野指针、assert 与传址实战
java·c语言·开发语言
蒸鱼Yuzheng7 小时前
设备端性能工件可靠导出:断点续传、哈希、manifest 与失败恢复
android·自动化测试·python·adb·数据完整性
实心儿儿7 小时前
Qt — Qt 事件
开发语言·qt
周杰偷奶茶7 小时前
【Java】数据类型与变量
java·开发语言
code斗7 小时前
Java数据结构:堆详解
java·开发语言·数据结构
重生之小比特7 小时前
【C++进阶】map和set
java·开发语言·c++