Home » Python » Python programs

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

Python | Counting word occurrence: Here, we are going to learn how to find the occurrence of a word in the given text/paragraph in Python programming language?
Submitted by IncludeHelp, on April 24, 2020

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.

Consider the below program implemented for counting occurrences of just one word in a text.

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.








Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.