查看“Python实例解析:文本词频统计”的源代码
←
Python实例解析:文本词频统计
跳转至:
导航
,
搜索
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
用户
您可以查看与复制此页面的源代码。
==实例解析:文本词频统计== 在很多情况下,会遇到这样的问题:对于一篇给 定文章,希望统计其中多次出现的词语,进而概 要分析文章的内容。 这个问题的解决可用于对网 络信息进行自动检索和归档。 在信息爆炸时代,这种归档或分类十分有必要。 这就是“词频统计”问题。 ===算法分析=== 我们可以采用字典来解决词频统计问题。 *输入:从文件中读取一篇文章。 *处理:采用字典数据结构,统计词语出现频率。 [[文件:Java6-3.png|500px]] *输出:文章中最常出现的十个单词及出现次数。 ==英文词频统计== 英文文本以空格或标点符号来分隔词语获得单词并统计数量相对容易。 英文文本下载:https://python123.io/resources/pye/hamlet.txt 代码: <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() #print(words) #print(type(words)) counts = {} #print(type(counts)) for word in words: counts[word] = counts.get(word,0) + 1 items = list(counts.items())#将字典转换为列表 print(item[0]) 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实例解析:文本词频统计
。
导航菜单
个人工具
登录
命名空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
最近更改
随机页面
帮助
工具
链入页面
相关更改
特殊页面
页面信息