Occurence of a string in a text python -


there numerous posts occurence of substring in python, can't find occurrence of string in text.

teststr = "suppose have large text , trying find specific occurences of words"  #suppose search term a, expect output of program be: print teststr.myfunc("a") >>1 

since there 1 concrete reference string "a" in entire input. count() won't since counts substrings well, output is:

print teststr.count() >>3 

can done?

you can use collections after splitting string.

from collections import counter print counter(teststr.split()) 

the output

counter({'you': 2, 'a': 1, 'and': 1, 'words': 1, 'text': 1, 'some': 1, 'the': 1, 'large': 1, 'to': 1, 'suppose': 1, 'are': 1, 'have': 1, 'of': 1, 'specific': 1, 'trying': 1, 'find': 1, 'occurences': 1}) 

to count of specific substring a use,

from collections import counter res = counter(teststr.split()) print res['a'] 

if count needs case-insensitive, convert substrings using upper() or lower before counting.

res= counter(i.lower() in teststr.split()) 

Comments