【问题标题】:Python NLTK :: Intersecting words and sentencesPython NLTK :: 相交的单词和句子
【发布时间】: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


【解决方案1】:

您评估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

【讨论】:

  • 实际上,这个想法不是返回总和,而是与输入更相似的一个 sentence,因此 len() 最适合目标。但是谢谢你,你教会了我一些关于交点和计数之间的区别的好东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多