2016-06-11 101 views
0

我正在使用NLTK - 一个特定的工具包来操作语料库文本,并且我定义了一个函数来交叉用户输入和莎士比亚的话。Python 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', '.']] 

我想找到它包含了大部分出现用户字的句子,并返回了一句。我想:

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'列表中的第一个'sent'项目。 – 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()最适合客观。但是谢谢你,你教给我一些关于交叉点和计数之间差异的好消息。 –