user3636636
user3636636

Reputation: 2499

Find particular words in a string, Python

Create a function that, Given Two arguments: A text as a string and words as a set of strings, returns the number of words from the set, that are contained in the string.

Eg. count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"}) == 3

My Attempt:

import re
def count_words(text, words):
count = 0
for i in words:
    x = re.compile('.*'+i+'.*')
    if x.search(text):
        count +=1
return count

I assume this has been answered several times before, but i just could not find a relevant answer, so my apologies. Any help would be appreciated, thanks

Upvotes: 2

Views: 2028

Answers (1)

inspectorG4dget
inspectorG4dget

Reputation: 114035

def count_words(text, words):
    answer = 0
    for i in range(len(text)):
        if any(text[i:].startswith(word) for word in words):
            answer += 1
    return answer

If you want it to be insensitive to letter cases in the text:

def count_words(text, words):
    text = text.lower()
    answer = 0
    for i in range(len(text)):
        if any(text[i:].startswith(word) for word in words):
            answer += 1
    return answer

Of course, this can be done with a one-liner:

sum(text.count(word) for word in words)

Upvotes: 8

Related Questions