您正在将一系列列表传递给矢量化器,这就是您收到AttributeError. 相反,您应该传递一个可迭代的字符串。从CountVectorizer 文档中:
fit_transform(raw_documents, y=None)
学习词汇词典并返回术语-文档矩阵。
这相当于先拟合后变换,但更有效地实现。
参数: raw_documents:可迭代
产生 str、 unicode 或文件对象的迭代。
要回答您的问题,CountVectorizer可以使用ngram_range(以下生成二元组)创建 N-gram:
count_vect = CountVectorizer(ngram_range=(2,2))
corpus = [
'This is the first document.',
'This is the second second document.',
]
X = count_vect.fit_transform(corpus)
print(count_vect.get_feature_names())
['first document', 'is the', 'second document', 'second second', 'the first', 'the second', 'this is']
更新:
既然您提到您必须使用 NLTK 生成 ngram,我们需要覆盖CountVectorizer. 即,analyzer将原始字符串转换为特征:
分析器:字符串、{'word'、'char'、'char_wb'} 或可调用
[...]
如果传递了一个可调用对象,则它用于从未处理的原始输入中提取特征序列。
由于我们已经提供了 ngram,一个恒等函数就足够了:
count_vect = CountVectorizer(
analyzer=lambda x:x
)
结合 NLTK ngrams 和 CountVectorizer 的完整示例:
corpus = [
'This is the first document.',
'This is the second second document.',
]
def build_ngrams(text, n=2):
tokens = text.lower().split()
return list(nltk.ngrams(tokens, n))
corpus = [build_ngrams(document) for document in corpus]
count_vect = CountVectorizer(
analyzer=lambda x:x
)
X = count_vect.fit_transform(corpus)
print(count_vect.get_feature_names())
[('first', 'document.'), ('is', 'the'), ('second', 'document.'), ('second', 'second'), ('the', 'first'), ('the', 'second'), ('this', 'is')]