>>> phrases = ["I'm so happy with myself lately!", "Johnny, im so sad, so very sad, call me", "i feel like crap. SO ANGRY!!!!"]
>>> words = ["happy", "sad", "angry", "jumpy"]
>>>
>>> for phrase in phrases:
... print phrase
... print {word: phrase.count(word) for word in words}
...
I'm so happy with myself lately!
{'jumpy': 0, 'angry': 0, 'sad': 0, 'happy': 1}
Johnny, im so sad, so very sad, call me
{'jumpy': 0, 'angry': 0, 'sad': 2, 'happy': 0}
i feel like crap. SO ANGRY!!!!
{'jumpy': 0, 'angry': 0, 'sad': 0, 'happy': 0}
>>> phrases = ["I'm so happy with myself lately!", "Johnny, im so sad, so very sad, call me", "i feel like crap. SO ANGRY!!!!"]
>>> words = ["happy", "sad", "angry", "jumpy"]
>>> for phrase in phrases:
for word in words:
if word in phrase:
print('"{0}" is in the phrase "{1}".'.format(word, phrase))
"happy" is in the phrase "I'm so happy with myself lately!".
"sad" is in the phrase "Johnny, im so sad, so very sad, call me".
非常简单、直接的解决方案:
对于
^{pr2}$word_counts = [{word: phrase.count(word) for word in words} for...
行,您需要Python2.7+。如果出于某种原因,使用的是<;Python 2.7,请将该行替换为以下内容:相关问题 更多 >
编程相关推荐