Skip to content Skip to sidebar Skip to footer

Check For (whole Only) Words In String

Training on Checkio. The task is called Popular words. The task is to search for words from a list (of strings) in a given string. For example: textt='When I was One I had just beg

Solution 1:

you'd be better off splitting your sentence, then count the words, not the substrings:

textt="When I was One I had just begun When I was Two I was nearly new"
wwords=['i', 'was', 'three', 'near']
text_words = textt.lower().split()
result = {w:text_words.count(w) for w in wwords}

print(result)

prints:

{'three': 0, 'i': 4, 'near': 0, 'was': 3}

if the text has punctuation now, you're better off with regular expressions to split the string according to non-alphanum:

import re

textt="When I was One, I had just begun.I was Two when I was nearly new"

wwords=['i', 'was', 'three', 'near']
text_words = re.split("\W+",textt.lower())
result = {w:text_words.count(w) for w in wwords}

result:

{'was': 3, 'near': 0, 'three': 0, 'i': 4}

(another alternative is to use findall on word characters: text_words = re.findall(r"\w+",textt.lower()))

Now if your list of "important" words is big, maybe it's better to count all the words, and filter afterwards, using the classical collections.Counter:

text_words = collections.Counter(re.split("\W+",textt.lower()))
result = {w:text_words.get(w) for w in wwords}

Solution 2:

Your simple solution would be this one:

from collections import Counter

textt="When I was One I had just begun When I was Two I was nearly new".lower()
wwords=['i', 'was', 'three', 'near']

txt = textt.split()

keys = Counter(txt)

for i in wwords:
    print(i + ' : ' + str(keys[i]))

Post a Comment for "Check For (whole Only) Words In String"