Computer Science
Write a program to count the words "to" and "the" present in a text file "Poem.txt".
Python File Handling
15 Likes
Answer
Let the file "Poem.txt" include the following sample text:
To be or not to be, that is the question.
The quick brown fox jumps over the lazy dog.
To infinity and beyond!
The sun sets in the west.
To be successful, one must work hard.
to_count = 0
the_count = 0
with open("Poem.txt", 'r') as file:
for line in file:
words = line.split()
for word in words:
if word.lower() == 'to':
to_count += 1
elif word.lower() == 'the':
the_count += 1
print("count of 'to': ", to_count)
print("count of 'the': ", the_count)
Output
count of 'to': 4
count of 'the': 5
Answered By
8 Likes
Related Questions
A file sports.dat contains information in following format:
Event - Participant
Write a function that would read contents from file sports.dat and creates a file named Atheletic.dat copying only those records from sports.dat where the event name is "Atheletics".A file contains a list of telephone numbers in the following form:
Arvind 7258031 Sachin 7259197The names contain only one word, the names and telephone numbers are separated by white spaces. Write program to read a file and display its contents in two columns.
Write a function AMCount() in Python, which should read each character of a text file STORY.TXT, should count and display the occurrence of alphabets A and M (including small cases a and m too).
Example :
If the file content is as follows :
Updated information
As simplified by official websites.The EUCount() function should display the output as :
A or a : 4
M or m : 2Write a program to count the number of upper-case alphabets present in a text file "Article.txt".