How to Count Word Frequency in a Given String in Python


This example will teach us how to count the number of times the word in the given string appears.

Source Code

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

str = input("Please input the string: ")
word = input("Please input the word to be counted: ")
wordList = str.split(" ")
count = 0
for i in wordList:
    if i == word:
        count += 1
print("The number of {} appears is {}".format(word, count))

Output:

Please input the string: Hello Python
Please input the word to be counted: Python
The number of Python appears is 1
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement