使用NLTK生成双字母组合

2024-10-05 11:45:39 发布

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

我试图生成给定句子的bigram列表,例如,如果我键入

    To be or not to be

我希望程序生成

     to be, be or, or not, not to, to be

我试过下面的代码,但是给了我

<generator object bigrams at 0x0000000009231360>

这是我的代码:

    import nltk
    bigrm = nltk.bigrams(text)
    print(bigrm)

那我怎么才能得到我想要的呢?我想要一个上面这些词的组合列表(是,是,还是不是,不是,是)。


Tags: orto代码程序列表键入notbe
2条回答

^{}返回一个bigram的迭代器(特别是生成器)。如果需要列表,请将迭代器传递给list()。它还期望从一系列项中生成bigram,因此在传递文本之前必须将其拆分(如果您没有这样做的话):

bigrm = list(nltk.bigrams(text.split()))

要以逗号分隔打印它们,可以(在python 3中):

print(*map(' '.join, bigrm), sep=', ')

如果在python 2上,则例如:

print ', '.join(' '.join((a, b)) for a, b in bigrm)

请注意,仅用于打印不需要生成列表,只需使用迭代器即可。

下面的代码为给定的句子生成一个bigram列表

>>> import nltk
>>> from nltk.tokenize import word_tokenize
>>> text = "to be or not to be"
>>> tokens = nltk.word_tokenize(text)
>>> bigrm = nltk.bigrams(tokens)
>>> print(*map(' '.join, bigrm), sep=', ')
to be, be or, or not, not to, to be

相关问题 更多 >

    热门问题