用Python字典简单实现词频统计

1 问题

在生活中我们偶尔会碰到一个任务要求:需要统计一本小说中某个人的名字,或者某个关键词在文章中出现的次数,由于字数太多我们不可能人为的慢慢去计数,这时我们可以根据程序来自动获得其次数。

2 方法

根据字典的性质,以此关键词或人名作为字典的键,出现次数作为其字典的值。首先对文中进行分词,对每个词建立键,以此遍历每个词。如果字典中有该词,则其值+1否则设为1并创建该词的键。

代码清单 1

forexamle="You are you are,you are the trouble I'm in"
forexample = forexamle.lower()
words = forexample.split()
word_frequence={}
for word in words:
   if word in word_frequence.keys():  #判断当前访问的单词是否在字典中
       word_frequence[word] += 1  #如果存在,则将该单词对应键的值加一
   else:
       word_frequence[word] = 1 #如果不存在则创建键,并赋值为一
print(word_frequence)
#get()实现
forexamle="You are you are,you are the trouble I'm in"
forexample = forexamle.lower()
words = forexample.split()
word_frequence={}
for i in range(len(words)):
   word_frequence[words[i]] = word_frequence.get(words[i],0) + 1
   #get()方法 如果取不到则为0;
print(word_frequence)
#内置库
from collections import Counter
forexamle="You are you are,you are the trouble I'm in"
forexample = forexamle.lower()
words = forexample.split()
print(dict(Counter(words)))

3 结语

针对如何用python实现简单词频统计的问题,提出上述几个方面的知识和操作,通过亲自实验,证明该方法是有效的,本文使用这种方法解决了统计一本小说中某个人的名字,或者某个关键词在文章中出现的次数等问题,但方法并不简便,还有考虑不周的地方,未来可以继续研究更加简洁方便的代码进行处理。

你可能感兴趣的:(python,开发语言)