2017-02-08 8 views
1

단어 목록에 단어가 나오는 횟수를 찾는 함수를 작성하고 있습니다. 달성하기 쉽다.Python :리스트에서 문장의 출현을 찾는 방법

그러나, 나는 할 수있다, 여러 단어가 포함 된 문자열의 발생을 확인하는 방법을 알아 내려고 이틀 동안 그것을 있었다 두 개 이상의

그래서 예를 들면 말 문자열은 다음과 같습니다

"hello bye" 
하고 목록이다 :

["car", "hello","bye" ,"hello"] 

함수의 값을 반환한다 1 요소 "안녕하세요"와 "안녕"오직 한번 발생하기 때문에 콘 꾸준히.


내가 솔루션에 왔 가장 가까운

인덱스 주어진 두 개의 요소를 결합 것이다
words[0:2] = [' '.join(words[0:2])] 

을 사용하고 있습니다. 그러나 주어진 입력이 색인이 아닌 요소 자체가되므로 이것은 잘못된 것입니다.

나를 올바른 방향으로 안내 할 수 있습니까?

+0

[XY 문제] (http://meta.stackexchange.com/a/66378/344593)와 같이 들립니다.이 코드로 해결하려는 문제를 설명해 주시겠습니까? 핵심 이슈에 대한 더 쉬운 해결책이있을 수 있습니다. – TemporalWolf

+0

열거 형의 for 루프를 사용하여 내용 * 및 * 색인을 유지할 수 있습니다. http://stackoverflow.com/questions/22171558/what-does-enumerate-mean –

답변

1

두 가지 가능성이 있습니다.

## laboriously 

lookFor = 'hello bye' 
words = ["car", "hello","bye" ,"hello", 'tax', 'hello', 'horn', 'hello', 'bye'] 

strungOutWords = ' '.join(words) 

count = 0 
p = 0 
while True: 
    q = strungOutWords [p:].find(lookFor) 
    if q == -1: 
     break 
    else: 
     p = p + q + 1 
     count += 1 

print (count) 

## using a regex 

import re 
print (len(re.compile(lookFor).findall(strungOutWords))) 
+0

내 대답을 편집하여 다른 가능성을 추가하십시오. –

1

문자열을 주 목록에서 연속 요소의 조인과 일치시킵니다.

my_list = ["car", "hello","bye" ,"hello"] 
sentence = "hello bye" 
word_count = len(sentence.split()) 
c = 0 

for i in range(len(my_list) - word_count + 1): 
    if sentence == ' '.join(my_list[i:i+word_count]): 
     c+=1 

c의 최종 값이 보류 될 것입니다 :

:

>>> c 
1 

당신이 한 줄 찾고있는 경우로 zipsum을 사용할 수 있습니다, 아래 샘플 코드는

>>> my_list = ["car", "hello","bye" ,"hello"] 
>>> sentence = "hello bye" 
>>> words = sentence.split() 

>>> sum(1 for i in zip(*[my_list[j:] for j in range(len(words))]) if list(i) == words) 
1 
0

문제를 줄이면 다른 문자열 내에있는 문자열의 출현을 계산할 것을 제안합니다. ~.

words = ["hello", "bye", "hello", "car", "hello ", "bye me", "hello", "carpet", "shoplifter"] 
sentence = "hello bye" 
my_text = " %s " % " ".join([item for sublist in [x.split() for x in words] for item in sublist]) 


def count(sentence): 
    my_sentence = " %s " % " ".join(sentence.split()) 
    return my_text.count(my_sentence) 


print count("hello bye") 
>>> 2 
print count("pet shop") 
>>> 0 
+0

지금은 작동하지 않지만, 애완 동물 샵'등. –

+0

좋은 캐치, 통찰력을 바탕으로 내 대답을 편집하고 텍스트에 몇 가지 전처리를 추가했습니다. 도움이되기를 바랍니다! – kardaj

1

이 부분을 두 부분으로 나눕니다.

def ngrams(l, n): 
    return list(zip(*[l[i:] for i in range(n)])) 

우리는 이제 쉽게 2, 3 또는 4 그램을 얻을 수 있습니다 :

>>> ngrams(["car", "hello","bye" ,"hello"], 2) 
[('car', 'hello'), ('hello', 'bye'), ('bye', 'hello')] 
>>> ngrams(["car", "hello","bye" ,"hello"], 3) 
[('car', 'hello', 'bye'), ('hello', 'bye', 'hello')] 
>>> ngrams(["car", "hello","bye" ,"hello"], 4) 
[('car', 'hello', 'bye', 'hello')] 
첫째, 우리는 주어진리스트의을 ngrams를 반환하는 기능을 설정, 즉, n 개의 연속적인 요소의 하위 목록입니다

각 항목은 튜플로 구성됩니다.

지금 튜플에 문구 'hello bye'합니다이 두 단어를 가지고 있기 때문에

>>> as_tuple = tuple('hello bye'.split()) 
>>> as_tuple 
('hello', 'bye') 
>>> len(as_tuple) 
2 

, 우리는 문장에서 bigrams을 생성하고, 일치하는 bigrams의 수를 계산해야합니다.이 모든 것을 일반화 할 수 있습니다.

def ngrams(l, n): 
    return list(zip(*[l[i:] for i in range(n)])) 

def count_occurrences(sentence, phrase): 
    phrase_as_tuple = tuple(phrase.split()) 
    sentence_ngrams = ngrams(sentence, len(phrase_as_tuple)) 
    return sentence_ngrams.count(phrase_as_tuple) 

print(count_occurrences(["car", "hello","bye" ,"hello"], 'hello bye')) 
# prints 1 
관련 문제