Python NLTK ::相交的单词和句子

时间:2016-06-11 03:23:13

标签: python nltk nested-lists

我正在使用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

我做错了什么?

提前感谢。

1 个答案:

答案 0 :(得分: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