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]) 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -