954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Word Frequency Help

Hello,

I have to count the number of words in a .txt file.
Here is my program so far

import string
ofile=open(raw_input("Please enter the name of a text file :"))
s=ofile.readlines()
print s
word_freq={}

word_list=string.split(s)

for word in word_list:
    count=word_freq.get(string.lower(word),0)
    word_freq[string.lower(word)]=count+1

keys=word_freq.keys()
keys.sort()

for word in keys:
    print word,word_freq[word]


As of now I'm getting a 'AttributeError: 'list' object has no attribute 'split''

Please help me!

Thanks so much,

Joey

Joey7
Newbie Poster
4 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

You need a string to split. I updated your code a little ...

#import string  # old stuff

#ofile=open(raw_input("Please enter the name of a text file :"))
# open a text file you have for testing ...
ofile = open("atest.txt")
# read text in as one string s
s = ofile.read()
print s
print

word_freq = {}

# split text string s on white spaces
word_list = s.split()

for word in word_list:
    count = word_freq.get(word.lower(),0)
    word_freq[word.lower()] = count + 1

keys = word_freq.keys()
keys.sort()

for word in keys:
    print word, word_freq[word]
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: