0

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

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by vegaseat
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]
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.