python - How to find the count of a word in a string? -


i have string "hello going hello am". want find how many times word occur in string. example hello occurs 2 time. tried approach prints characters -

def countword(input_string):     d = {}     word in input_string:         try:             d[word] += 1         except:             d[word] = 1      k in d.keys():         print "%s: %d" % (k, d[k]) print countword("hello going hello am") 

i want learn how find word count.

if want find count of individual word, use count:

input_string.count("hello") 

use collections.counter , split() tally words:

from collections import counter  words = input_string.split() wordcount = counter(words) 

Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -