How to Find Most Frequent Character in a String with Python


In this example we will show how to quickly find the character which has the highest occurrence frequency in a given string.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# getTheMostValueOfList.py
# Python, find the character which has the highest occurrence frequency

import re
from collections import Counter

def get_max_value(text):
    text = text.lower()
    # remove non-letter character
    result = re.findall('[a-zA-Z]', text)  
    count = Counter(result)  
    
    # Counter({'l': 3, 'o': 2, 'd': 1, 'h': 1, 'r': 1, 'e': 1, 'w': 1})
    count_list = list(count.values())
    max_value = max(count_list)
    max_list = []

    for k, v in count.items():
        if v == max_value:
            max_list.append(k)
    
    # sort in ascending order and get the first value
    max_list = sorted(max_list)
    return max_list[0]

print('The character which occurs in "How do you do?" most frequently is: ' + get_max_value("How do you do?"))

Ouput:

The character which occurs in "How do you do?" most frequently is: o
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments