关于sort和Counter方法的应用

2018-03-24  本文已影响0人  不_一
#!/usr/bin/env python
# -*- coding:utf-8 -*-

from collections import Counter
import re

with open('a.txt', 'r', encoding='utf-8') as f:
    txt = f.read()
f = lambda x: x.lower()
c = Counter(map(f, re.split('\W+', txt)))  # \W 匹配非字母或数字或下划线
ret = c.most_common(10)
print(ret)

# 按照字符串的多少排序

from collections import Counter, OrderedDict

str1 = 'sageeurjweojgnoer'

s = Counter(str1)
# [('s', 1), ('a', 1), ('g', 2), ('e', 4), ('u', 1), ('r', 2), ('j', 2), ('w', 1), ('o', 2), ('n', 1)]
t = list(s.items())
t.sort(key=lambda x: x[1], reverse=True)
l = []

for k, v in t:
    print(k, v)
    for j in range(v):
        l.append(k)

print(''.join(l))
上一篇 下一篇

猜你喜欢

热点阅读