Answers for "python count words in file"

1

python count words in file

import re
# Open file in read mode
input_file = open("C:\Users\fawaz\Desktop\data.txt", "rt")
"""
Get each line from file
Then decompose it into words
Update count with nb of words
per line.
"""
count = 0
for line in input_file: 
	words = re.split("s+", line.strip())  # words separated by any nb of white spaces
	print(words)
	count += len(words)

print("Number of words in input file:", count)

input_file.close()
Posted by: Guest on February-09-2022

Python Answers by Framework

Browse Popular Code Answers by Language