基于NLTK自然语言处理子列表的前两项过滤列表列表

2024-09-29 21:59:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我用这段代码生成了NLTK中的三叉树及其频率列表

tokens = nltk.wordpunct_tokenize(docs)
from nltk.collocations import *
trigram_measures = nltk.collocations.TrigramAssocMeasures()
finderT = TrigramCollocationFinder.from_words(tokens)
scoredT = finderT.score_ngrams(trigram_measures.raw_freq)

给定一个由两个单词组成的用户定义的“input”,我想对列表scoredT进行归档,以返回那些输入与scoredT中子列表的前两项匹配的值

斯考特看起来像这样

[(('out', 'to', 'the'), 2.7147650642313413e-05),
(('proud', 'of', 'you'), 2.7147650642313413e-05)]

所以如果输入等于'out to',我想过滤列表以返回'the'

我试过了

matches = filter(scoredT[0:len(scoredT)][0:1]==input, scoredT)

但是获取以下错误TypeError:“bool”对象不可调用


Tags: thetofrom列表inputout代码生成trigram
1条回答
网友
1楼 · 发布于 2024-09-29 21:59:35

scoredT[0:len(scoredT)][0:1]==inputscoredT第一元素与input进行比较。所以它是布尔型的。然后将其传递给filter,这要求第一个参数是布尔值函数,因此出现错误。Python的方式:

matches = [(trigram, score) for (trigram, score) in scoredT if trigram[:2] == input]

您还需要确保input是一个元组。你知道吗

相关问题 更多 >

    热门问题