Given a Text or the string as the input to the program you have to count the number of words in the text and return it using a python program.
Write a python program that counts and returns the number of words in a given text
Let's ask a user to enter the string using input function call and store the string into a variable named text.
text = input("Enter a String : ")
The user enters a string, splits the string and stores the list into a new variable text list. Use the string built in functions split to to convert the string to a list of words.
text_list = text.split()
Using the print function call print the length of new variable text list this will give us the count of words present in the text
print(len(text_list))
Full program
=====================`
text = input("Enter a String : ")
text_list = text.split()
print("Count of Words in Text is :", len(text_list))
Output
===================
Enter a String : brown fox jumped from mountain
Count of Words in Text is : 5
The program can be modified to use for loop to get the count of number of words in a text using a counter
text = input("Enter a String : ")
text_list = text.split()
count = 0
for _ in text_list:
count += 1
print("Count of Words in Text is : ", count)
OUTPUT
=================
Enter a String : how are you ?
Count of Words in Text is : 4
Write a python program that counts and returns the number of words in a given text file
You can modify the above program to accept a text filename from the user and count the number of words in a text file and print it
filename = input("Enter a Filename : ")
readfd = open(filename, "r")
data = readfd.read()
readfd.close()
text_list = data.split()
count = 0
for _ in text_list:
count += 1
print("Count of Words in Text File is : ", count)
Input text file : sample.txt
================================
the fox is hiding
Output
=================
Enter a Filename : sample.txt
Count of Words in Text File is : 4
0 Comments