How to Count Occurrence Frequency of Words in a String in Python


Here this example will show us how to use dictionaries counts the frequency of words that appear in a given string. 

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

str = input("Please input the string separated by SPACE: ")
wordList = str.split()
wordFreq = [wordList.count(word) for word in wordList]
print("The frequency of words are: ", dict(zip(wordList, wordFreq)))

Output:

Please input the string separated by SPACE: a b c d c a b a d
The frequency of words are: {'c': 2, 'b': 2, 'd': 2, 'a': 3}

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement