中文字符频率统计python_python统计字符串出现最多的字母及其出现次数

统计字符串出现最多的字母及其出现次数

另外如果次数相同按字母顺序排序。

方法1

可以使用自定义键对c.most_common()进行排序,该键首先考虑频率的降序,然后考虑字母的降序(请注意lambda x: (-x[1], x[0]) ):

from collections import Counter

def ordered_letters(s, n=3):

c = Counter(s.replace(' ', ''))

top_n = sorted(c.most_common(), key=lambda x: (-x[1], x[0]))[:n]

for i, t in enumerate(top_n):

c, f = t

if i == 0: print('1st most frequent', c + '.', 'Appearances:', f)

elif i == 1: print('2nd most frequent', c + '.', 'Appearances:', f)

elif i == 2: print('3rd most frequent', c + '.', 'Appearances:', f)

else: print(str(i + 1) + 'th most frequent', c + '.', 'Appearances', f)

sent = "china construction bank"

ordered_letters(sent, 5)

# 1st most frequent n. Appearances: 4

# 2nd most frequent c. Appearances: 3

# 3rd most frequent a. Appearances: 2

# 4th most frequent i. Appearances 2

# 5th most frequent o. Appearances 2

方法2

常规方式对Counter的元组进行排序, 但第一个参数-count本身被取反。 这将产生一个反向列表,但第二个元组元素将按字母顺序排序。 然后取最后n个项目。

from collections import Counter

ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4])

def ordered_letters(s, n=3):

ctr = Counter(c for c in s if c.isalpha())

ctr = sorted(ctr.items(), key=lambda x: (-x[1], x[0]))[:n]

for index,value in enumerate(ctr):

print "{:s} most frequent: '{:}'. Appearances: {:}".format(ordinal(index+1),value[0],value[1])

s = "achina aconstruction banck"

ordered_letters(s, n=3)

结果:

1st most frequent: 'a'. Appearances: 4

2nd most frequent: 'c'. Appearances: 4

3rd most frequent: 'n'. Appearances: 4

要想成为python这领域的高手,必须了解和弄懂python常见问题。要我们来进行python高手修炼吧。或者你有更好的问题可以留言。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值