Shivkumar - 20 days ago 9
Python Question

# Print count (word occurrence) from a random text (Print hackerearth)

I am trying to find the count of occurrence of fixed word from any given string

Fixed word = 'hackerearth'

random string may be s = 'aahkcreeatrhaaahkcreeatrha'

now from string we can generate 2-times hackerearth.

I have written some code to find the count of (h,a,e,r,c,k,t)letters in string:

Code:

``````word = list(raw_input())
print word

h = word.count('h')
a = word.count('a')
c = word.count('c')
k = word.count('k')
e = word.count('e')
r = word.count('r')
t = word.count('t')

if (h >= 2 and a >= 2 and e >= 2 and r >=2) and (c >= 1 and k >= 1 and t >=1 ):
hc = h/2
ac = a/2
ec = e/2
rc = r/2

num_words = []
num_words.append(hc)
num_words.append(ac)
num_words.append(ec)
num_words.append(rc)
num_words.append(c)
num_words.append(k)
num_words.append(t)

print num_words
``````

output:

``````[2, 4, 2, 2, 2, 2, 2]
``````

From above output list ,I want to calculate the total occurrence of word

Can somebody help me to get total count of fixed word and any other way to make this code easier

You could utilize `Counter`:

``````from collections import Counter

s = 'aahkcreeatrhaaahkcreeatrha'
word = 'hackerearth'

wd = Counter(word)
sd = Counter(s)

print(min((sd.get(c, 0) // wd[c] for c in wd), default=0))
``````

Output:

``````2
``````

Above code will create two `dict` like counters where letters are keys and their occurrence are values. Then it will use generator expression to iterate over the letters found in the word and for each letter generate the ratio. `min` will pick the lowest ratio and `default` value of `0` is used for case where there are no common letters.