Ravi S. Ranjan
Ravi S. Ranjan

Reputation: 43

Count each string in an string

I am having a text..

text= ''' One of the best ways to make yourself happy in the present is to recall happy times from the past memories ''' I want to match each word in the match list and count their occurrence.

match=['happy birthday to me' , 'john sent me the memo app' , 'self time' , 'call the rom']

Example- In first iteration i.e, happy birthday to me...

happy is counted 2 times , birthday is counted 0 times , to is counted 2 times , me is counted 1 time. ('me' in memories)

I want the result as-

happy(2) birthday(0) to(2) me(1)
john(0) sent(1) me(1) the(3) memo(1) app(2)
self(1) time(1)
call(1) the(3) rom(1)

I tried this...

for textmatch in match:
    num=text.count(textmatch)
    textmatch= textmatch +'(' + str(num) +')'
    print(textmatch)

But this doesnt do the job.

Upvotes: 0

Views: 34

Answers (2)

Austin
Austin

Reputation: 26039

You can do a list comprehension to form a list of words and their frequency:

text= ''' One of the best ways to make yourself happy in the present is to recall happy times from the past memories '''
match=['happy birthday to me' , 'john sent me the memo app' , 'self time' , 'call the rom']

print([[(y, text.count(y)) for y in x.split()] for x in match])

Upvotes: 1

Joe Iddon
Joe Iddon

Reputation: 20414

You need to iterate over each word in the match strings. This can be achieved by splitting it (on spaces).

The other nifty trick is to print out each word with the optional end argument set to just a space (' '). This means that they all stay on one line until a plain print() call is made which moves to the next line.

for textmatch in match:
    for word in textmatch.split():
        num=text.count(word)
        print(word + '(' + str(num) + ')', end=' ')
    print()

Test in the interpreter:

>>> text= ''' One of the best ways to make yourself happy in the present is to 
...            recall happy times from the past memories '''
>>> 
>>> match=['happy birthday to me' , 'john sent me the memo app' , 'self time' , 'call the rom']
>>> for textmatch in match:
...     for word in textmatch.split():
...         num=text.count(word)
...         print(word + '(' + str(num) + ')', end=' ')
...     print()
... 
happy(2) birthday(0) to(2) me(2) 
john(0) sent(1) me(2) the(3) memo(1) app(2) 
self(1) time(1) 
call(1) the(3) rom(1) 

Upvotes: 1

Related Questions