使用 NLTK 生成二元语法
Generate bigrams with NLTK
我正在尝试生成给定句子的二元组列表,例如,如果我键入,
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)
那么我怎样才能得到我想要的东西呢?我想要一个像上面这样的词的组合列表 (to be, be or, or not, not to, to be)。
nltk.bigrams()
returns 双字母组合的迭代器(特别是生成器)。如果你想要一个列表,将迭代器传递给 list()
。它还需要一系列项目来生成双字母组,因此您必须在传递文本之前拆分文本(如果您没有这样做):
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
很晚了,但这是另一种方式。
>>> from nltk.util import ngrams
>>> text = "I am batman and I like coffee"
>>> _1gram = text.split(" ")
>>> _2gram = [' '.join(e) for e in ngrams(_1gram, 2)]
>>> _3gram = [' '.join(e) for e in ngrams(_1gram, 3)]
>>>
>>> _1gram
['I', 'am', 'batman', 'and', 'I', 'like', 'coffee']
>>> _2gram
['I am', 'am batman', 'batman and', 'and I', 'I like', 'like coffee']
>>> _3gram
['I am batman', 'am batman and', 'batman and I', 'and I like', 'I like coffee']
我正在尝试生成给定句子的二元组列表,例如,如果我键入,
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)
那么我怎样才能得到我想要的东西呢?我想要一个像上面这样的词的组合列表 (to be, be or, or not, not to, to be)。
nltk.bigrams()
returns 双字母组合的迭代器(特别是生成器)。如果你想要一个列表,将迭代器传递给 list()
。它还需要一系列项目来生成双字母组,因此您必须在传递文本之前拆分文本(如果您没有这样做):
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
很晚了,但这是另一种方式。
>>> from nltk.util import ngrams
>>> text = "I am batman and I like coffee"
>>> _1gram = text.split(" ")
>>> _2gram = [' '.join(e) for e in ngrams(_1gram, 2)]
>>> _3gram = [' '.join(e) for e in ngrams(_1gram, 3)]
>>>
>>> _1gram
['I', 'am', 'batman', 'and', 'I', 'like', 'coffee']
>>> _2gram
['I am', 'am batman', 'batman and', 'and I', 'I like', 'like coffee']
>>> _3gram
['I am batman', 'am batman and', 'batman and I', 'and I like', 'I like coffee']