查看“Python 文本词频统计”的源代码
←
Python 文本词频统计
跳转至:
导航
,
搜索
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
用户
您可以查看与复制此页面的源代码。
==词频统计原理== 我们可以采用字典来解决制品统计问题。 *输入:从文件中读取一篇文章。 *处理:采用字典数据结构,统计词语出现频率。 *输出:文章中最常出现的十个单词及出现次数。 ==英文词频统计== 英文文本以空格或标点符号来分隔词语获得单词并统计数量相对容易。 代码: <nowiki>#e10.1CalHamlet.py def getText(): txt = open("hamlet.txt", "r").read() txt = txt.lower() for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~': txt = txt.replace(ch, " ") #将文本中特殊字符替换为空格 return txt hamletTxt = getText() words = hamletTxt.split() counts = {} for word in words: counts[word] = counts.get(word,0) + 1 items = list(counts.items()) items.sort(key=lambda x:x[1], reverse=True) for i in range(10): word, count = items[i] print ("{0:<10}{1:>5}".format(word, count))</nowiki> ==中文词频分析== ===jieba库的使用=== *相关内容请参见:[[Python jiaba库的使用]] ===中文词频分析=== <nowiki>#e10.3CalThreeKingdoms.py import jieba excludes = {}#{"将军","却说","丞相"} txt = open("三国演义.txt", "r", encoding='utf-8').read() words = jieba.lcut(txt) counts = {} for word in words: if len(word) == 1: #排除单个字符的分词结果 continue else: counts[word] = counts.get(word,0) + 1 for word in excludes: del(counts[word]) items = list(counts.items()) items.sort(key=lambda x:x[1], reverse=True) for i in range(15): word, count = items[i] print ("{0:<10}{1:>5}".format(word, count))</nowiki>
返回至
Python 文本词频统计
。
导航菜单
个人工具
登录
命名空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
最近更改
随机页面
帮助
工具
链入页面
相关更改
特殊页面
页面信息