【问题标题】:Empty vocabulary for single letter by CountVectorizerCountVectorizer 的单个字母的空词汇表
【发布时间】:2017-09-21 22:02:14
【问题描述】:

试图将字符串转换为数值向量,

### Clean the string
def names_to_words(names):
    print('a')
    words = re.sub("[^a-zA-Z]"," ",names).lower().split()
    print('b')

    return words


### Vectorization
def Vectorizer():
    Vectorizer= CountVectorizer(
                analyzer = "word",  
                tokenizer = None,  
                preprocessor = None, 
                stop_words = None,  
                max_features = 5000)
    return Vectorizer  


### Test a string
s = 'abc...'
r = names_to_words(s)
feature = Vectorizer().fit_transform(r).toarray()

但是当我遇到:

 ['g', 'o', 'm', 'd']

有错误:

ValueError: empty vocabulary; perhaps the documents only contain stop words

这样的单字母字符串似乎有问题。 我该怎么办? 谢谢

【问题讨论】:

  • 那你想做什么?将这些单字母单词包含在您的词汇表中吗?

标签: python nlp vectorization feature-extraction countvectorizer


【解决方案1】:

CountVectorizer 中的默认 token_pattern 正则表达式选择至少有 2 个字符的单词为 stated in documentation

token_pattern:字符串

表示什么构成“令牌”的正则表达式,仅在以下情况下使用 分析器 == '单词'。默认的正则表达式选择 2 个或更多的标记 字母数字字符(标点符号被完全忽略并且总是 视为标记分隔符)。

source code of CountVectorizerr"(?u)\b\w\w+\b

将其更改为 r"(?u)\b\w+\b 以包含 1 个字母的单词。

将您的代码更改为以下内容(在上述建议中包含token_pattern 参数):

Vectorizer= CountVectorizer(
                analyzer = "word",  
                tokenizer = None,  
                preprocessor = None, 
                stop_words = None,  
                max_features = 5000,
                token_pattern = r"(?u)\b\w+\b")

【讨论】:

  • 为什么会隐式设置“2个或更多字符”这个条件?今天这只是咬我,我很高兴我找到了你的答案。很有帮助!
猜你喜欢
  • 2016-10-18
  • 2020-11-30
  • 2015-05-07
  • 2015-12-16
  • 2016-09-25
  • 2020-01-15
  • 2019-08-29
  • 2018-12-12
  • 2017-10-11
相关资源
最近更新 更多