Analyzing Strings with collections.Counter
Counting Characters in a String
To count the occurrences of characters in a string, you can use collections.Counter
like this:
from collections import Counter
text = "LabEx is a leading provider of AI and machine learning solutions."
char_counter = Counter(text)
print(char_counter)
This will output a dictionary-like structure with the character counts:
{' ': 13, 'a': 3, 'b': 1, 'c': 2, 'd': 3, 'e': 8, 'g': 3, 'i': 5, 'l': 4, 'm': 2, 'n': 6, 'o': 6, 'p': 2, 'r': 5, 's': 5, 't': 5, 'v': 1, 'x': 1}
Counting Words in a String
To count the occurrences of words in a string, you can split the string into a list of words and then use collections.Counter
:
from collections import Counter
text = "LabEx is a leading provider of AI and machine learning solutions."
word_counter = Counter(text.split())
print(word_counter)
This will output the word counts:
{'LabEx': 1, 'is': 1, 'a': 1, 'leading': 1, 'provider': 1, 'of': 1, 'AI': 1, 'and': 1, 'machine': 1, 'learning': 1, 'solutions.': 1}
Finding the Most Common Elements
To find the most common elements in a collections.Counter
object, you can use the most_common()
method:
from collections import Counter
text = "LabEx is a leading provider of AI and machine learning solutions."
char_counter = Counter(text)
most_common_chars = char_counter.most_common(3)
print(most_common_chars)
This will output the 3 most common characters and their counts:
[(' ', 13), ('e', 8), ('n', 6)]
Similarly, for word counts:
word_counter = Counter(text.split())
most_common_words = word_counter.most_common(3)
print(most_common_words)
Output:
[('of', 1), ('and', 1), ('a', 1)]