[Tutor] Please comment on this code...WORD FREQUENCY COUNTER
Asrarahmed Kadri
ajkadri at googlemail.com
Mon Oct 23 23:03:10 CEST 2006
Folks,
I have written a program which calculates teh frequency of each word that
appears in a file. I would like to have your feedback.
*This program only handles .txt files. I want it to handle word documents
also. How to accomplish this ..???*
Thanks.
Regards.
Asrarahmed
*Code is as under:*
**
fname = raw_input("Enter the file name to be opened")
fd = open(fname, 'r')
done = 0
dict1 = {} # create an empty dictionary to hold word as a key
and its freq. as the value
while not done:
aLine = fd.readline()
if aLine != "" :
string1 = aLine.split()
for item in string1:
dict1[item] = 0 #enter each word as the key and intial value as
0
else:
done = 1
fd.seek(0,0) # go to the beginning
of the file
done = 0
while not done:
aLine = fd.readline() # read one line at a time
if aLine != "" :
string1 = aLine.split() # split the line into a
list of words...
for item in string1:
dict1[item] += 1 # counter for the word
else:
done = 1
print "Word \t Frequency"
for k,v in dict1.iteritems(): # print the word and its
corresponding frequency
print k, "\t\t", v
--
To HIM you shall return.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20061023/5fa61181/attachment.html
More information about the Tutor
mailing list