python的思维就是让我们用尽可能少的代码来解决问题。对于词频的统计,就代码层面而言,实现的方式也是有很多种的。之所以单独谈到统计词频这个问题,是因为它在统计和数据挖掘方面经常会用到,尤其是处理分类问题上。故在此做个简单的记录。
统计的材料如下:
document = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under']
直接使用dict来进行统计(遍历+循环)
word_count = {}
for word in document:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
更优雅的实现方式
#假如字典中不存在给定的键,则返回参数中提供的默认值;反之,则返回字典中保