Skip to content

Python count word occurrences in string

  • by

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

Python counts word occurrences in string

Simple example code counts 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 the 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading