adsa lila
adsa lila

Reputation: 115

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 results output of single word,but i need only the overall word count of all the words in the file and also the overall wordcount of words provided by the user.

Code:

name = raw_input("Enter the query x ")
name1 = raw_input("Enter the query y ")
file=open("xmlfil.xml","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for k,v in wordcount.items():
    print k, v

for name in file.read().split():
    if name not in wordcount:
        wordcount[name] = 1
    else:
        wordcount[name] += 1
for k,v in wordcount.items():
    print k, v

for name1 in file.read().split():
    if name1 not in wordcount:
        wordcount[name1] = 1
    else:
        wordcount[name1] += 1
for k,v in wordcount.items():
    print k, v

Upvotes: 1

Views: 7810

Answers (2)

ForceBru
ForceBru

Reputation: 44828

MyFile=open('test.txt','r')
words={}
count=0
given_words=['The','document','1']
for x in MyFile.read().split():
    count+=1
    if 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.

Upvotes: 3

ferhatelmas
ferhatelmas

Reputation: 3978

You can get what you need easily via Counter

from collections import Counter

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

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

Upvotes: 2

Related Questions