How to count the frequency of words repeated in a text file?

azon333 Source

I am supposed to use functions. Basically, the task consists in copying all the words from a text file to a dictionary and count the number of times it is repeated.

So if the key which is the word is in the dictionary, we count or else add to dictionary with count 1.

Here is a code i tried. However nothing prints:

def wordCount(file1):
    file1 = open('declarationofInd.txt','r')
    mydict = {}
    file1.strip()
    mydict[key] = file1
    mydict.keys()
    print mydict
pythonfunctiondictionarycount

Answers

answered 3 years ago JAW #1

I think you want to count the number of times a word appears in a text doc.

file=open('yourfilehere')
text=file.read().split()
mydict={}
for word in text:
    if word not in mydict.keys():
        mydict[word]=1
    else:
        count=mydict[word]
        mydict[word]=count+1
print(mydict)

If this is what you are intending to create, then this should work for your intentions. If you are doing this not in IDLE or command prompt, then you should call the function, preferably in a new file.

By the way, I would advise you to make your question clearer as well as research the topic more before posting.

comments powered by Disqus