两个列表,一个单词,一个短语

2024-09-27 07:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我有两个单子,一个词,像这样:

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

等等

然后是一个短语列表,比如:

^{pr2}$

我想用第一个单词列表,来查找词组列表中单词的出现率。我不在乎我是否提取实际的单词,用空格隔开,或者只是它们出现的次数。在

从我所了解的情况来看,重新模块和过滤器似乎是一个好办法?在

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


Tags: 模块过滤器列表情况单词次数单子空格
3条回答
>>> 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".
>>> 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}]
>>> 

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

^{pr2}$

相关问题 更多 >

    热门问题