DEV Community

Cover image for WORD COUNTER: A simple python script that counts a specific word in text file
John Johnson Okah
John Johnson Okah

Posted on

4 2

WORD COUNTER: A simple python script that counts a specific word in text file

During a rainy and boring morning, I decided to write an algorithm that displays how many times a word appears in the bible.


To start with, I searched for a kjv bible in a text file and found one that was in this format:
bible.txt

Genesis 1:1 In the beginning God created the heaven and the earth.
Genesis 1:2 And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters.
Genesis 1:3 And God said, Let there be light: and there was light.
...
Revelation 22:21    The grace of our Lord Jesus Christ be with you all. Amen.
Enter fullscreen mode Exit fullscreen mode

Then I wrote this code to do the word count magic for me:
search_bible.py

search = input("Search for: ")
total_count = 0
with open("bible.txt") as bible:
    for line in bible:
        bible_verse = line.split("\t")[-1].lower()
        verse_count = bible_verse.count(search.lower())
        total_count += verse_count
print(f"{search} appears {total_count} times")
Enter fullscreen mode Exit fullscreen mode

Testing the program (where script and text file are in same directory)

Alt Text


Feel free to share your insight on the comment and don't forget to like.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
softwaresennin profile image
Lionel♾️☁️

wooow!! thanks so much for this. It is really good!!

great job!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs