Counting occurences of words that appear in a list using Python -
i have appended excel sheet values list using xlrd. called list a_master. have text file words want count occurrences of appear in list (i called file dictionary , theirs 1 word per line). here code:
with open("dictionary.txt","r") f: line in f: print "count " + line + str((a_master).count(line))
for reason though, count comes 0 every count word exists in text file. if write out count 1 of these words myself:
print str((a_master).count("server"))
it counts occurrences no problem.i have tried
print line
in order see if seeing words in dictionary.txt file correctly , is.
lines read file terminated newline character. there may white space @ end. better strip out whitespace before doing lookup
with open("dictionary.txt","r") f: line in f: print "count " + line + str((a_master).count(line.strip()))
note ideally, searching list linear , may not optimal in cases. think collections.counter suitable situation depicted.
re-interpret list dictionary key item , value occurrence passing through collections.counter
shown below
a_master = collections.counter(a_master)
and can re-write code as
from itertools import imap open("dictionary.txt","r") f: line in imap(str.strip, f): print "count {} {}".format(line, a_master[line])