在使用python sklearn.feature_extraction.text的CountVectorizer时,发现会自动剔除掉单字的中文和只有一个字母的英文。
#CountVectorizer convert a collection of text documents to a matrix of token counts
from sklearn.feature_extraction.text import CountVectorizer
vectorizer=CountVectorizer()
cor_test=["贵 磨脚 这么 磨脚 磨","20 元 运费","鞋面 皱 很 皱"]
vv=vectorizer.fit_transform(cor_test)
print(vv.shape)
(3, 5)
#获取所有词
words=vv.get_feature_names()
print(words)
['20', '磨脚', '运费', '这么', '鞋面'] #单字“贵”,“磨”,“元”,“皱”,“很”没有被计算出现次数
corpus=['This is a document.', 'This is the a second document.', 'And the third one.', 'Is this the first document?']
v=vectorizer.fit_transform(corpus)
v.get_feature_names()
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this'] #单字母的“a”没有被计算出现次数
单字被自动剔除的原因:
token_pattern : string
Regular expression denoting what constitutes a “token”, only used if
analyzer == 'word'
. The default regexp select tokens of 2 or more alphanumeric characters (punctuation is completely ignored and always treated as a token separator).
CountVectorizer的参数token_pattern保留2个或2个以上字母数字字符的词。
那应该怎样定义token_pattern对应的正则表达式来保留单字呢?
对英文来说,可以设置vectorizer=CountVectorizer(token_pattern='\w{1,}')
对中文来说,可以设置vectorizer=CountVectorizer(token_pattern='[\u4e00-\u9fa5_a-zA-Z0-9]{1,}') 正则表达式匹配中文或数字或字母出现一次会更多次
但,还有一些情况的中文也会被自动剔除掉。
我在处理一份电商类的文本时,发现以下词出现在语料中,但是没有出现在CountVectorizer转换后的词中。
例如: 'CHN', 'XL', '88A', 'EMS', 'VIP', 'CD','大S', 'ID', 'T恤'等。
请教该怎么解决?非常感谢!