9

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

### 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

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

4

1 回答 1

13

CountVectorizer 中的默认 token_pattern 正则表达式选择具有至少 2 个字符的单词,如文档中所述

token_pattern : 字符串

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

CountVectorizer 的源代码r"(?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")
于 2017-04-25T08:23:34.350 回答