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高手修炼吧。或者你有更好的问题可以留言

赞(4) 打赏
特别声明:除特殊标注,本站文章均为原创,遵循CC BY-NC 3.0,转载请注明出处。三伏磨 » python统计字符串出现最多的字母及其出现次数

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏