Python Program to Count Total Number of Words in a Text File
Q. Write a program to count total number of words available in a text file in python.
file: “text.txt”
Solution:
# print total number of words available in a text file def read_data(): f = open("text.txt", 'r') s = f.read() x = s.split() print(str(len(x)) +" "+"Words") read_data()
Output:
#53 Words
Explanation: Here we have defined a function read_data(). Inside read_data() function we have also created a file object “f” and opened our text file in read mode ie. “r” mode.
In next step, we have initialized all the values to variable “s“. And used read() function to read our file word by word. The read() function return the output in string format.
Note: Here inside function, we have used split() and len() function which returns the list and total length of object respectively. Here “s” is our file object.
split() method will separate each word from space and store them in list “x”.
So, now we have the complete text data in list format of string data type. If we can perform len() function operation in list then it will return us the total number of data available ie. words available in our list. Hence we can get total count of words.
-
Programming questions on Text Files
- WAP to define a method to read text document line by line.
- WAP to define a method in python to read lines from a text file starting with an alphabet F.
- WAP to define a method to count number of lines starting with an alphabet F.
- WAP to define a method which display only those lines starting with an alphabet A or F.
- WAP to define a method to display only those lines which are bigger than 50 characters.
- WAP to define a method to count total number of characters in our text file.
- WAP to define a method which counts the occurrence of particular word in a text file.
- WAP to define a method which only print the words having more than 5 characters.
- WAP to define a method which counts the occurrence of “is”, “to” in a text file.
Programming questions on Binary Files