Topic: Count Words in Each Line of Text File Python Program
# Python program to count # number of words in each line of a text file separately # Input filename, open it in # read mode. display its cntents # count and display number of words # www.EasyCodeBook.com file_name = input("Enter file name:") file1 = open(file_name, "r") word_count = 0 i = 0 str1 = "" print("Contents of file " + file_name + " are:") # display and count number of words in each line of text file for line in file1: i+=1 print(line, end='') words_in_line = len(line.split()) str1 = str1 + "Words in Line No: " + str(i) + " are : " + str(words_in_line)+"\n" word_count+=words_in_line print('\n\n ' + str1) print('\n\nTotal Number of words in this file are = ' + str(word_count)) file1.close()
Enter file name:d://example.txt
Contents of file d://example.txt are:
this is example text file
this is line 2
this is last line
Words in Line No: 1 are : 5
Words in Line No: 2 are : 4
Words in Line No: 3 are : 4
Total Number of words in this file are = 13
You will also like the following Python File Programs:
- Count Words in Text File Python Program
- Count Lines in Text File Python Program
- Python Text File Program To Count Vowels
- Python File Program Count Characters in Text File
- Python Exception Handling FileNotFoundError
- Python Text File Read and Show Contents Program
- Python file program read numbers write squares
How This Python File Program Works?
Count Words in Each Line of Text File
- First of all the user will input a file name.
- Open this text file in Read mode.
- Use for loop to read the text file one line at a time.
- Use split() method to get words in each line
- Find the number of words in each line using len() function
- Display number of words in the current line with line number.
- Move to the next line.
- Repeat for all lines in the text file.
13,072 total views, 13 views today
Pingback: Find Occurrences of Each Word in Text File Python Program | EasyCodeBook.com
Pingback: Python File Copy Program using shutil.filecopy | EasyCodeBook.com