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

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]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.