Python高效编程-统计列表中元素频率

from collections import Counter
from random import randint
import os
import re

# 统计序列中元素出现的频率
data = [randint(0, 20) for _ in range(30)]
print(data)
c = dict.fromkeys(data, 0)
print(c)
for i in data:
    c[i] += 1
c2 = Counter(data)
print(c2)
print(c2[10]) # 显示10出现的频率
print(c2.most_common(3)) # 以list的形式列出出现频率最高的三组元素

# 统计文本文件中单词的出现频率
curDir = os.path.dirname(__file__) # 获取当前文件的所在目录
# txt = open(curDir + '/article.txt', 'r').read()
with open(curDir + '/article.txt', 'r') as f:
    txt = f.read()
c3 = Counter(re.split('\W+', txt)) # 以非单词字符为标志分割字符串,并将其转化为Counter对象
print(c3.most_common(10))

你可能感兴趣的:(Python基础)