2

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

1
  • 1
    Umm... since how and How are different strings, should the return value in your example be 2 instead of 3? Commented Aug 11, 2014 at 2:47

1 Answer 1

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

Comments

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.