Skip to content

Python count word occurrences in string

  • by

Use count() method with split to counts word occurrences in string in Python. First, split the string by spaces and store in list then use count() to find count of that word in list.

Python counts word occurrences in string

Simple example code count the number of occurrences of the given word in the string and print the number of occurrences of the word.

s = "Hello computer science portal Hello"
word = "Hello"

wordslist = list(s.split())
print(wordslist.count(word))

Output:

Python counts word occurrences in string

Time Complexity: O(n)
Auxiliary Space: O(n)

Counting occurrences of a word in a text file without count function

import string

frank = open('file.txt', 'r', encoding='utf-8')
frank_poem = frank.read()

frank_poem = frank_poem.translate(str.maketrans('', '', string.punctuation))

split_poem = frank_poem.split()

target_word = input("The word you would like to count in File: ")


def word_count(target_word):
    total = 0
    for word in split_poem:
        if word == target_word:
            total += 1
    return total


print(word_count(target_word))

Output:

The word you would like to count in File: Python
1

Do comment if you have any doubts or suggestions on this Python string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *