Skip to content Skip to sidebar Skip to footer

Counting Total Number Of Words In A Text File

I am new to python and trying to print the total number of words in a text file and the total number of specific words in the file provided by the user. I tested my code, but resul

Solution 1:

MyFile=open('test.txt','r')
words={}
count=0
given_words=['The','document','1']
for x in MyFile.read().split():
    count+=1if x in given_words:
        words.setdefault(x,0)
        words[str(x)]+=1    
MyFile.close()
print count, words

Sample output

17 {'1': 1, 'The': 1, 'document': 1}

Please do not name the variable to handle open() result file as then you'll overwrite the constructor function for the file type.

Solution 2:

You can get what you need easily via Counter

from collections import Counter

c = Counter()
withopen('your_file', 'rb') as f:
    for ln in f:
        c.update(ln.split())

total = sum(c.values())
specific = c['your_specific_word']

Post a Comment for "Counting Total Number Of Words In A Text File"