Nurdin
Nurdin

Reputation: 23893

Find specific keyword and count it in Python

I trying to find how many specific keyword in string but the output is not similar with the logic

input = raw_input('Enter the statement:') //I love u
keyword = raw_input('Enter the search keyword:') //love

count = 0

for i in input:
    if keyword in i:
        count = count + 1

print count
print len(input.split())

Expectation

1
3

Reality

0
3

Upvotes: 1

Views: 225

Answers (3)

Jared Goguen
Jared Goguen

Reputation: 9008

Let's look at the line for i in input. Here, input is a string which is an iterable in Python. This means you can do something like:

for char in 'string':
    print(char)
# 's', 't', 'r', 'i', 'n', 'g'

Instead, you can use the str.count method.

input.count(keyword)

As noted in a comment above, if you have the input "I want an apple" with the keyword "an", str.count will find two occurrences. If you only want one occurrence, you will need to split the input and then compare each word for equality.

sum(1 for word in input.split() if word == keyword)

Upvotes: 1

Mureinik
Mureinik

Reputation: 312086

input is a string, so iterating over it will give you each character individually. You probably meant to split it:

for i in input.split():

Note that using a list comprehension may be more elegant than a for loop:

count = len([x for x in input.split() if x in keyword])

Upvotes: 3

Tim S.
Tim S.

Reputation: 2257

You need to turn the statement into a list, like this:

input = raw_input('Enter the statement:').split()   //I love u
keyword = raw_input('Enter the search keyword:')     //love

count = 0

for i in input:
    if keyword in i:
        count = count + 1

print count
print len(input)

This will allow the loop to correctly identify your desired items.

Upvotes: 1

Related Questions