日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python統計序列和文件中元素的頻度_python

作者:AllardZhao ? 更新時間: 2022-06-24 編程語言

1、如何統計序列中元素的出現頻度

實際案例:

  • (1)某隨機序列[12, 5, 6, 4, 6, 5, 5, 7, ...] 中找到出現次數最高的3個元素,它們出現次數是多少?
  • (2)對某英文文章的單詞,進行詞頻統計,找到出現次數最高的10個單詞,它們出現次數是多少?

解決方案:

使用collections.Counter對象

將序列傳入Counter的構造器,得到Counter對象是元素頻度的字典。

Counter.most_common(n)方法得到頻度最高的n個元素的列表。

2、代碼演示

(1)某隨機序列 [12, 5, 6, 4, 6, 5, 5, 7, ...] 中找到出現次數最高的3個元素,它們出現次數是多少?

from random import randint
?
# 利用列表解析生成隨機序列
data = [randint(0, 20) for _ in range(30)]
print(data)
# 方法1:
'''
最終的統計結果肯定是一個字典,如:{2: 5, 4:9},
以data中每一個元素作為字典的鍵,0作為初始值,創建這樣一個字典
'''
c = dict.fromkeys(data, 0)
print(c)
# 對data進行迭代,進行統計
for x in data:
? ? c[x] += 1
print(c)
# 根據字典的值對字典項進行排序,并截取前3個元素
sort_dict = sorted(c.items(), key=lambda item: item[1], reverse=True)[0:3]
print(sort_dict)
? ??
# 方法2:
from collections import Counter
# 直接將序列傳給Counter構造器
c2 = Counter(data)
print(c2)
# 直接使用對象的most_common()方法直接找到頻度最高3個
print(c2.most_common(3)) ? ?

(2)對某英文文章的單詞,進行詞頻統計,找到出現次數最高的10個單詞,它們出現次數是多少?

from collections import Counter
# 導入正則表達式模塊
import re
?
# 讀取整個文件內容作為字符串
txt = open('word.txt').read()
print(txt)
# 對詞頻進行統計,首先需要進行分割把每一個字取出來
# 用非字母的字符作為分割,然后傳給Counter()進行統計
c3 = Counter(re.split('\W+', txt))
# 使用most_common()選取10個頻度最高單詞
print(c3.most_common(10))

原文鏈接:https://blog.csdn.net/qq_37189082/article/details/124417597

欄目分類
最近更新