0

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.

0

2 Answers 2

1

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) 
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

It works perfectly.. But can you make this more concise to read..Like happy(2) birthday(0) to(2) me(2)
@RaviSRanjan, If you have to do any manipulation on the result, you need to sacrifice the readability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.