Python实现结巴分词统计高频中文词汇
代码
1 # 读取文件 2 fn = open('youxi.txt', 'rt', encoding='utf-8') # 打开文件 3 string_data = fn.read() # 读出整个文件 4 fn.close() # 关闭文件 5 6 # 文本预处理 7 pattern = re.compile(u'\t|\n|\.|-|:|;|\)|\(|\?|"') # 定义正则表达式匹配模式 8 string_data = re.sub(pattern, '', string_data) # 将符合模式的字符去除 9 10 # 文本分词 11 seg_list_exact = jieba.cut(string_data, cut_all=False) # 精确模式分词 12 object_list = [] 13 14 # 分词并去除停用词 15 remove_words = set() 16 fr = open('stopword.txt', encoding = 'UTF-8') 17 for word in fr: 18 remove_words.add(str(word).strip()) 19 fr.close() 20 21 for word in seg_list_exact: # 循环读出每个分词 22 if word not in remove_words: # 如果不在去除词库中 23 object_list.append(word) # 分词追加到列表 24 25 # 词频统计 26 word_counts = collections.Counter(object_list) # 对分词做词频统计 27 word_counts_top10 = word_counts.most_common(100) # 获取前100最高频的词 28 print(word_counts_top10) # 输出检查
需要引入的库
1 import re # 正则表达式库 2 import collections # 词频统计库 3 import numpy as np # numpy数据处理库 4 import jieba # 结巴分词
文件内容示例
处理结果示例(前100)
好看请赞,养成习惯:) 本文来自博客园,作者:靠谱杨, 转载请注明原文链接:https://www.cnblogs.com/rainbow-1/p/15607928.html
欢迎来我的51CTO博客主页踩一踩 我的51CTO博客
文章中的公众号名称可能有误,请统一搜索:靠谱杨的秘密基地