Python Concordance program - alphabetical order -
i'm trying write program displays concordance file. should output unique words , frequencies in alphabetical order. have, it's not working. tips?
fyi - know nothing computer programming!! i'm taking class satisfy high school math endorsement requirement.
f = open(raw_input("enter filename: "), "r") mydict = {} linenum = 0 line in f: line = line.strip() line = line.lower() line = line.split() linenum += 1 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") key in sorted(mydict): print '%-15s: %-15d' % (key, mydict(key))
you need use mydict[key] getting dictionary. , since that's list, need use sum(mydict[key]) frequency (count)
f = "hello hello hello doing" mydict = {} linenum = 0 word in f.split(): if not word in mydict: mydict[word] = [] mydict[word].append(linenum) print "%-15s %-15s" %("word", "frequency") key in sorted(mydict): print '%-15s: %-15d' % (key, len(mydict[key])) results in:
word frequency : 1 doing : 1 hello : 3 : 1 : 1
Comments
Post a Comment