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
Thank you so much PhilW. I was having this problem from so many days, and i could not understand, what the error could be, because during the training, i did not find anything like this.
Indentation Fix: The content = file.read() line is properly indented to be part of the with block. This ensures that the file is read while it is still open.
Error Handling Suggestion (Optional): While you haven’t explicitly included error handling, if you want to guard against potential issues like a missing file or incorrect encoding, you can use a try-except block.
************************
filename = "book.txt"
word = input("Enter the word to count: ")
try:
with open(filename, 'r', encoding='utf-8') as file:
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
Thank you so much PhilW. I was having this problem from so many days, and i could not understand, what the error could be, because during the training, i did not find anything like this.
Indentation Fix: The content = file.read() line is properly indented to be part of the with block. This ensures that the file is read while it is still open.
Error Handling Suggestion (Optional): While you haven’t explicitly included error handling, if you want to guard against potential issues like a missing file or incorrect encoding, you can use a try-except block.
************************
filename = "book.txt"
word = input("Enter the word to count: ")
try:
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}'.")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
except UnicodeDecodeError:
print(f"Error: Unable to decode the file '{filename}'. Check the encoding.")