Open In App

Python – Words Frequency in String Shorthands

Last Updated : 10 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Word frequency in String Shirthands in Python typically refers to calculating how often words appear in a given string using various concise and efficient methods.

Using collections.Counter

Using collections.Counter allows you to count the frequency of each character in a string. By leveraging this, we can identify vowels and replace them with a specific character, like ‘K’, based on their frequency or presence in the string.

from collections import Counter

# Input string
s = "hello world hello everyone"

# Calculate word frequencies using Counter
w_freq = Counter(s.split())

print(w_freq)

Output
Counter({'hello': 2, 'world': 1, 'everyone': 1})

Explanation

  • Counter is used to count the frequency of each word in the string s by splitting the string into individual words using split().
  • output, {'hello': 2, 'world': 1, 'everyone': 1}, shows that the word “hello” appears twice, while “world” and “everyone” appear once each.

Using dict.get() with a for loop

Using dict.get() with a for loop allows you to efficiently count occurrences of each character or word in a string. The get() method retrieves the current count, and if the character or word isn’t in the dictionary yet, it returns a default value (usually 0).

# Input string
s = "hello world hello everyone"

# Initialize an empty dictionary to store word frequencies
w_freq = {}

# Calculate word frequencies using a for loop
for word in s.split():
    w_freq[word] = w_freq.get(word, 0) + 1

# Print the result
print(w_freq)

Output
{'hello': 2, 'world': 1, 'everyone': 1}

Explanation

  • for loop iterates over each word in the string s, splitting it into words. For each word, dict.get() is used to fetch the current frequency (or 0 if the word is not yet in the dictionary), and then the count is incremented.
  • The output is {'hello': 2, 'world': 1, 'everyone': 1}, which shows the frequency of each word in the string.

Using List Comprehension with collections.Counter

Using list comprehension with collections.Counter allows you to efficiently count the frequency of elements by transforming the data (such as characters or words in a string) and applying Counter to generate frequency counts.

from collections import Counter

# Input string
s = "hello world hello everyone"

# Calculate word frequencies using Counter and list comprehension
w_freq = Counter([word for word in s.split()])

# Print the result
print(w_freq)

Output
Counter({'hello': 2, 'world': 1, 'everyone': 1})

Explanation

  • This code uses a list comprehension to split the string into words and create a list of those words. The list is then passed to Counter, which calculates the frequency of each word.
  • The result, Counter({'hello': 2, 'world': 1, 'everyone': 1}), displays the word counts in the input string.

Using map() and Counter

Using map() with Counter combines functional programming and frequency counting. It applies a transformation to each element of an iterable using map() before passing the transformed iterable to Counter

from collections import Counter

# Input string
s = "hello world hello everyone"

# Calculate word frequencies using map and Counter
w_freq = Counter(map(str, s.split()))

print(w_freq)

Output
Counter({'hello': 2, 'world': 1, 'everyone': 1})

Explanation

  • Splits the string into words and applies str to ensure each item is treated as a string (though unnecessary here since split() already produces strings).
  • Counts the occurrences of each word and stores the result as a Counter object


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg