【发布时间】:2016-10-12 02:13:39
【问题描述】:
我正在使用 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
我做错了什么?
提前致谢。
【问题讨论】:
-
我认为
return语句应该在for循环之外。否则,该函数将返回hamlet列表中的第一个sent项。
标签: python nltk nested-lists