To solve this problem, we need to count the number of words in a given text file. A word is defined as a sequence of characters separated by any whitespace (spaces, tabs, newlines). We will handle common errors like missing files to ensure the function is robust.
Approach
- Function Definition: Create a function that takes a filename as input.
- File Handling: Use the
withstatement to open the file (ensures automatic closure). - Read Content: Read the entire content of the file.
- Split into Words: Split the content into words using
split()(splits on any whitespace). - Count Words: Return the length of the list of words.
- Error Handling: Catch common exceptions like
FileNotFoundErrorto inform the user and handle other unexpected errors.
Solution Code
def count_words_in_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
words = content.split()
return len(words)
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
return 0
except Exception as e:
print(f"An unexpected error occurred: {e}")
return 0
# Example usage:
# filename = "sample.txt"
# print(f"Number of words in {filename}: {count_words_in_file(filename)}")
Explanation
- File Handling: The
withstatement ensures the file is closed properly after reading, even if an error occurs. - Word Splitting: The
split()method without arguments splits the content into words by any whitespace (spaces, tabs, newlines), which aligns with standard word count definitions. - Error Handling: The function catches
FileNotFoundErrorto notify the user if the file doesn't exist, and other exceptions to handle unexpected issues gracefully.
This approach is efficient and handles edge cases, making it a reliable solution for counting words in a text file.


作者声明:本文包含人工智能生成内容。