Project Level 1: Beginner
This project is designed for beginner learners who are still learning and practicing Python fundamentals.
Project Description
Create a Python program to count the occurrences of any given word in the book stored in this text file.
Expected Output
The user can enter any word (e.g., snow), and the program should find out how many occurrences of that word exist in the book.txt file and print out a message:
Learning Benefits
File Handling: Learn how to open, read, and close text files.
String Manipulation: Practice working with strings and string methods like
split()
,count()
, etc.Input and Output: Learn to take user input and display output to the console.
Prerequisites
Required Libraries: No libraries are needed for this project.
Required Files: No files are needed for this project.
IDE: You can use any IDE on your computer to code the project.
Danger Zone
Once you code the project, compare it with our two solutions given in the button below.
This is my code :
filename = "book.txt"
word = input("Enter the word to count: ")
# Use the correct encoding (utf-8 is common)
with open(filename, 'r', encoding='utf-8') as file:
content = file.read()
words = content.split()
count = words.count(word)
print(f"The word '{word}' appears {count} times in the file '{filename}'.")
I added utf-8 first since it's the most common encoding. otherwise I got an error UnicodeDecodeError caused by a mismatch between the encoding used by the book.txt file and the default encoding used by Python