目录
问题引入:
原理:
基本流程:
词频统计
①录入待统计的句子
②分割为多个单词
③创建字典
利用Python内置库快速实现词频统计
全部代码
普通方法
方法二:get()实现
内置库实现
Python字典方法-汇总:
①创建空字典
②查看字典的长度
③增删改查
1)增加
2)修改
3)删除
4)查询某个字典的值
问题引入:
在生活中我们偶尔会碰到一个任务要求:
需要统计一本小说中某个人(主角)名字,或者某个关键词在文章中出现的次数,由于字数太多我们不可能人为的慢慢去计数,这时我们可以根据程序来自动获得其次数。
原理:
根据字典的性质,以此关键词或人名作为字典的键,出现次数作为其字典的值。
基本流程:
首先对文中进行分词->对每个词建立键->以此遍历每个词->如果字典中有该词->则其值+1否则设为1并创建该词的键
词频统计
①录入待统计的句子
forexamle="You are you are,you are the trouble I'm in"
forexample = forexamle.lower() #将所有字母转化为小写形式
②分割为多个单词
words = forexample.split()
③创建字典
用于后续记录各单词的频次
word_frequence={}
思路:如果该单词已经在字典中存在(键存在)则对应的键加一
如果该单词不存在,则创建键并值设置为1
for word in words:
if word in word_frequence.keys(): #判断当前访问的单词是否在字典中
word_frequence[word] += 1 #如果存在,则将该单词对应键的值加一
else:
word_frequence[word] = 1 #如果不存在则创建键,并赋值为一
利用Python内置库快速实现词频统计
from collections import Counter
导入Conter,可以将列表直接转化为已经统计好的类似于频数字典的Counter类型
实际用法如下:
forexamle="You are you are,you are the trouble I'm in"
forexample = forexamle.lower()
words = forexample.split()
print(dict(Counter(words)))
全部代码
普通方法
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)))
两种输出的结果相同,使用Counter更方便快捷。
Python字典方法-汇总:
①创建空字典
dict1={}
②查看字典的长度
len(dict1)
③增删改查
1)增加
再已创建字典的情况下,直接输入键和值加入
In [1]: dict1['example']='a'
dict1
Out[1]: {'example': 'a'}
2)修改
直接通过键覆盖
In [2]: dict1['example']='b'
dict1
Out[2]: {'example': 'b'}
3)删除
del dict1['example'] # 删除键 'Name'
dict1.clear() # 清空字典
del dict1 #直接删除字典
4)查询某个字典的值
#直接输入键
dict1['example']
Out[94]: 'b'以上是本人的个人总结,如有错误请各位大佬批评指正!!