2

好的,所以我有两个列表,一个是单词,如下所示:

["happy", "sad", "angry", "jumpy"]

ETC

然后是短语列表,如下所示:

["I'm so happy with myself lately!", "Johnny, im so sad, so very sad, call me", "i feel like crap. SO ANGRY!!!!"]

我想使用第一个单词列表来查找短语列表中单词的出现次数。我不在乎我是否拉出实际的单词,用空格分隔,或者只是它们出现的次数。

根据我的调查,似乎 re 模块和过滤器是要走的路?

另外,如果我对我需要什么的解释不清楚,请告诉我。

4

3 回答 3

4
>>> 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}
于 2012-07-08T16:33:34.700 回答
2

非常简单,直接的解决方案:

>>> 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".
于 2012-07-08T16:25:02.023 回答
1
>>> 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"]
>>> words_in_phrases = [re.findall(r"\b[\w']+\b", phrase.lower()) for phrase in phrases]
>>> words_in_phrases
[["i'm", 'so', 'happy', 'with', 'myself', 'lately'], ['johnny', 'im', 'so', 'sad', 'so', 'very', 'sad', 'call', 'me'], ['i', 'feel', 'like', 'crap', 'so', 'angry']]
>>> word_counts = [{word: phrase.count(word) for word in words} for phrase in words_in_phrases]
>>> word_counts
[{'jumpy': 0, 'angry': 0, 'sad': 0, 'happy': 1}, {'jumpy': 0, 'angry': 0, 'sad': 2, 'happy': 0}, {'jumpy': 0, 'angry': 1, 'sad': 0, 'happy': 0}]
>>> 

对于 line word_counts = [{word: phrase.count(word) for word in words} for...,您需要 Python 2.7+。如果由于某种原因,您使用的是 < Python 2.7,请将该行替换为以下内容:

>>> word_counts = [dict((word, phrase.count(word)) for word in words) for phrase in words_in_phrases]
于 2012-07-08T16:50:28.393 回答