2012-07-08 2 views
2

확인 문구 중 하나, 그래서 나는과 같이, 두 개의리스트, 단어 중 하나가 :과 같이, 다음두 목록, 단어 중 하나,

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

그리고 문구의 목록을 :

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

첫 번째 단어 목록을 사용하여 구문 목록에서 단어의 발생을 찾으려합니다. 실제 단어를 공백으로 구분하거나 여러 번 나눠서 처리하는 것은 상관하지 않습니다.

내가 조사한 내용을 보면 필터뿐 아니라 모듈도 사용할 수있는 것으로 보입니다.

또한 내가 필요한 내용에 대한 설명이 명확하지 않은 경우 알려 주시기 바랍니다.

+1

이것은 다른 질문보다 분명합니다. –

+0

다시 또는 필터가 필요하지 않습니다. 내장 연산자 'in'및 str.count는 효율적으로 (순서대로) 작업을 수행합니다. 아래의 katrielalex 및 poke 솔루션은 두 가지 접근 방식을 모두 보여줍니다. 물론, 다시 당신을 위해 일할 수 있지만 칼이 할 캐논을 사용하는 것입니다 :-) – GeneralBecos

+2

@GeneralBecos : 그는 단어로 각 구문을 분할하는 정규식이 필요할 수 있습니다. "나는 미국인이 될지도 모른다"에서 "an"이 아니라면, "an"이라는 단어가 그 구절에 없더라도 true를 반환 할 것입니다. –

답변

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} 
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". 
+0

예,하지만 인스턴스를 계산하고 싶습니다. 그래서 Johnny 상태에서, 나는 하나 이상의 것을 기록 할 필요가있다. 또한 정규 표현식을 연결할 수도 있습니다. –

+1

일치하는 항목으로 인쇄를 쉽게 변경할 수 있습니다. 당신의 질문에 따르면 당신은 그들과 함께 무엇을해야하는지 상관하지 않으므로 다음 번에는 더 구체적이어야합니다. – poke

+0

왜 downvote? – poke

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}] 
>>> 

라인 word_counts = [{word: phrase.count(word) for word in words} for...를 들어, 2.7 이상 파이썬이 필요합니다. 어떤 이유에서든 < Python 2.7을 사용하는 경우 해당 행을 다음과 같이 바꾸십시오.

관련 문제