sklearn CountVectorizer 单字

在使用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恤'等。

请教该怎么解决?非常感谢!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值