Q:

Python program to count occurrence of a word in the given text

belongs to collection: Python String Programs

0

Given a text (paragraph) and a word whose occurrence to be found in the text/paragraph, we have to find the how many times word is repeated in the text.

Example:

    Input:
    text = "this is a book, this is very popular"
    word = "this"

    Output:
    'this' found 2 times.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

# Python program to count occurrence 
# of a word in text

# paragraph
text = """Lorem Ipsum is simply dummy text of the 
printing and typesetting industry. Lorem Ipsum has been 
the industry's standard dummy text ever since the 1500s"""

word = "text"
# searching word
count = 0
for w in text.split():
    if w == word:
        count = count + 1
# printing result
print("\'%s\' found %d times." %(word, count))

word = "is"
# searching word
count = 0
for w in text.split():
    if w == word:
        count = count + 1
# printing result
print("\'%s\' found %d times." %(word, count))

word = "Hello"
# searching word
count = 0
for w in text.split():
    if w == word:
        count = count + 1
# printing result
print("\'%s\' found %d times." %(word, count))

Output

'text' found 2 times.
'is' found 1 times.
'Hello' found 0 times.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to search for a pattern in string... >>
<< Python program to check whether a variable is a st...