I'm trying to write a program that displays a concordance for a file. It should output the unique words and their frequencies in alphabetical order. This is what I have, but it's not working. Tips?
FYI - I know NOTHING about computer programming!! I'm taking this class to satisfy a high school math endorsement requirement.
f = open(raw_input("Enter a filename: "), "r")
myDict = {}
linenum = 0
for line in f:
line = line.strip()
line = line.lower()
line = line.split()
linenum += 1
for word in line:
word = word.strip()
word = word.lower()
if not word in myDict:
myDict[word] = []
myDict[word].append(linenum)
print "%-15s %-15s" %("Word", "Line Number")
for key in sorted(myDict):
print '%-15s: %-15d' % (key, myDict(key))
You need to use myDict[key] for getting from a dictionary. And since that's a list, you need to use sum(myDict[key]) for frequency (count)
f = "HELLO HELLO HELLO WHAT ARE YOU DOING"
myDict = {}
linenum = 0
for word in f.split():
if not word in myDict:
myDict[word] = []
myDict[word].append(linenum)
print "%-15s %-15s" %("Word", "Frequency")
for key in sorted(myDict):
print '%-15s: %-15d' % (key, len(myDict[key]))
Results in:
Word Frequency
ARE : 1
DOING : 1
HELLO : 3
WHAT : 1
YOU : 1