如何在'word'和'char'分析器中使用sklearn CountVectorizer? http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html如何在'Word'和'char'分析器中使用sklearn CountVectorizer? - python
我可以通過word或char分別提取文本特徵,但是如何創建charword_vectorizer
?有沒有一種方法來組合矢量化器?或使用多個分析儀?
>>> from sklearn.feature_extraction.text import CountVectorizer
>>> word_vectorizer = CountVectorizer(analyzer='word', ngram_range=(1, 2), min_df=1)
>>> char_vectorizer = CountVectorizer(analyzer='char', ngram_range=(1, 2), min_df=1)
>>> x = ['this is a foo bar', 'you are a foo bar black sheep']
>>> word_vectorizer.fit_transform(x)
<2x15 sparse matrix of type '<type 'numpy.int64'>'
with 18 stored elements in Compressed Sparse Column format>
>>> char_vectorizer.fit_transform(x)
<2x47 sparse matrix of type '<type 'numpy.int64'>'
with 64 stored elements in Compressed Sparse Column format>
>>> char_vectorizer.get_feature_names()
[u' ', u' a', u' b', u' f', u' i', u' s', u'a', u'a ', u'ac', u'ar', u'b', u'ba', u'bl', u'c', u'ck', u'e', u'e ', u'ee', u'ep', u'f', u'fo', u'h', u'he', u'hi', u'i', u'is', u'k', u'k ', u'l', u'la', u'o', u'o ', u'oo', u'ou', u'p', u'r', u'r ', u're', u's', u's ', u'sh', u't', u'th', u'u', u'u ', u'y', u'yo']
>>> word_vectorizer.get_feature_names()
[u'are', u'are foo', u'bar', u'bar black', u'black', u'black sheep', u'foo', u'foo bar', u'is', u'is foo', u'sheep', u'this', u'this is', u'you', u'you are']
赦免了noobness,'r'\ w {3,}'是什麼意思?是否與'[a-zA-Z0-9_]'相同? – alvas
@alvas:'\ w'是'[a-zA-Z0-9_]'; '{3,}'表示「三個或更多」,所以它跳過短的標記。您可能想要嘗試使用不同的RE來捕捉令牌;這是我的基準之一。 –