2016-06-11 4 views
0

저는 코퍼스 텍스트를 조작하기위한 특정 툴킷 인 NLTK를 사용하고 있으며 사용자 입력과 셰익스피어의 단어를 교차시키는 함수를 정의했습니다.파이썬 NLTK :: 단어와 문장 교차하기

def shakespeareOutput(userInput): 

    user = userInput.split() 
    user = random.sample(set(user), 3) 

    #here is NLTK's method 
    play = gutenberg.sents('shakespeare-hamlet.txt') 

    #all lowercase 
    hamlet = map(lambda sublist: map(str.lower, sublist), play) 

print hamlet 반환 :

[ ['[', 'the', 'tragedie', 'of', 'hamlet', 'by', 'william', 'shakespeare', '1599', ']'], 
['actus', 'primus', '.'], 
['scoena', 'prima', '.'], 
['enter', 'barnardo', 'and', 'francisco', 'two', 'centinels', '.'], 
['barnardo', '.'], 
['who', "'", 's', 'there', '?']...['finis', '.'], 
['the', 'tragedie', 'of', 'hamlet', ',', 'prince', 'of', 'denmarke', '.']] 

I 사용자 단어의 대부분의 발생이 들어있는 문장을 찾아 문장을 반환하고 싶습니다. 나는 시도하고있다 :

bestCount = 0 
    for sent in hamlet: 
     currentCount = len(set(user).intersection(sent)) 
     if currentCount > bestCount: 
      bestCount = currentCount 
      answer = ' '.join(sent) 
      return ''.join(answer).lower(), bestCount 

은 함수를 호출 :

shakespeareOutput("The Actus Primus") 

반환 :

['The', 'Actus', 'Primus'] None

내가 잘못하고있는 중이 야 무엇을?

미리 감사드립니다.

+3

'return' 문은 'for' 루프 밖에 있어야한다고 생각합니다. 그렇지 않으면, 함수는'hamlet'리스트에서 가장 먼저'보낸'항목을 반환 할 것입니다. – Rahul

답변

2

귀하의 평가 방법은 currentCount입니다. 교차 세트는 일치하는 요소의 수가 아닌 일치하는 고유 한 요소의 수를 반환합니다.

>>> s = [1,1,2,3,3,4] 
>>> u = set([1,4]) 
>>> u.intersection(s) 
set([1, 4]) # the len is 2, however the total number matched elements are 3 

다음 코드를 사용하십시오.

bestCount = 0 

for sent in hamlet: 
    currentCount = sum([sent.count(i) for i in set(user)]) 
    if currentCount > bestCount: 
     bestCount = currentCount 
     answer = ' '.join(sent) 

return answer.lower(), bestCount 
+0

실제로, 아이디어는 합계가 반환되는 것이 아니라, 입력과 더 유사한 ONE ** 문장 **이므로 len()은 객관적으로 가장 적합합니다. 하지만 고맙습니다. 당신은 교차로와 카운트의 차이에 관해 나에게 멋진 것을 가르쳐 주셨습니다. –

관련 문제