Here’s a Python program to counts the occurrences of the words “to” and “the” in a text file called “Poem.txt”:
def count_words(filename): try: with open(filename, 'r') as file: content = file.read() # Convert all words to lowercase for case-insensitive matching content = content.lower() # Remove punctuation marks content = content.replace('.', '').replace(',', '').replace('!', '').replace('?', '') word_count = {'to': 0, 'the': 0} words = content.split() for word in words: if word == 'to': word_count['to'] += 1 elif word == 'the': word_count['the'] += 1 return word_count except FileNotFoundError: print(f"File '{filename}' not found.") return None filename = 'Poem.txt' result = count_words(filename) if result: print(f"Occurrences of 'to': {result['to']}") print(f"Occurrences of 'the': {result['the']}")
Make sure you have a text file named “Poem.txt” in the same directory as the Python script, and the file should contain the text you want to analyze. The program reads the file, converts all the words to lowercase for case-insensitive matching, removes punctuation marks, and then counts the occurrences of the words “to” and “the”. Finally, it prints the results.