Home 問題4 シェイクスピア
テキストの中にwords(辞書)のうち何個含まれているか。
count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"}) == 3
re.searchを使って、有った場合だけ数える。とても直線的
import re def count_words(text, words): x = 0 for i in words: match = re.search(i, text, flags=re.IGNORECASE) if match: x += 1 return x
もうちょっと短くしてみた。マッチする奴だけリストにして数える
def count_words(text, words): ok = [i for i in words if re.search(i, text, flags=re.IGNORECASE)] return len(ok)
このroopとif文は()の中でも使えるみたい。
return sum(1 for i in words if re.search(i, text, flags=re.IGNORECASE))
で、一番投票の多い答えは
sum(i in text.lower() for i in words)
前半がTrueの数を数えるやり方ですね。