问题1:
随机数列[12,5,8,7,8,9,4,8,5,...] 中出现次数最高的3个元素,他们出现的次数
问题2:
对某英文文章的单词,进行词频统计,找出出现次数最搞得10个单词,他们出现的次数是多少?
上面问题都是以字典的形式保存结果
如何解决问题1?
方法1:
#!/usr/bin/python3 from random import randint def count_seq(data): # 初始化统计结果字典,data中的key作为结果字典的key,0作为每个key的初始值
result_c = dict.fromkeys(data, 0) # 循环data,对字典中中碰到的值进行 +1 ,循环完成后就是结果
for x in data:
result_c[x] += 1
return result_c if __name__ == '__main__':
# 生成20个随机数
data = [randint(0, 20) for _ in range(20)]
print(data) # 结果
result_c = count_seq(data)
for i in result_c:
print(i, result_c[i])
方法2:
使用 collections下Counter对象
#!/usr/bin/python3 from random import randint
from collections import Counter def count_seq(data): # 创建Counter对象,并把打他传递进去
median_c = Counter(data) # 返回统计最大的3个数
return median_c.most_common(3) if __name__ == '__main__':
# 生成20个随机数
data = [randint(0, 20) for _ in range(20)]
print(data) # 结果
result_c = count_seq(data)
print(result_c, dict(result_c))
问题2如何解决?
import re
from collections import Counter def count_words():
# 读取文件
with open('english_article', 'r', encoding='utf-8') as data:
print()
# 文件单词分割
data_list = re.split('\W+', data.read())
# 单词统计
words = Counter(data_list)
# 取单词统计最大的10个值
return words.most_common(10) if __name__ == '__main__':
result = count_words()
print(result)