open a text file in python and count words code example

Example 1: count the frequency of words in a file

from collections import Counter
def word_count(fname):
        with open(fname) as f:
                return Counter(f.read().split())

print("Number of words in the file :",word_count("test.txt"))

Example 2: Python program that takes a text file as input and returns the number of words of a given text file

with open('file1.txt','r+') as f:
	numw=0
	for line in f:
		words= line.split()
		print(words)
		numw += len(words)
	print(numw)

Tags:

Java Example