如何强制 sklearn 的 CountVectorizer 不移除特殊字符(例如 #, @, , $ 或 %)

这是我的代码:

count = CountVectorizer(lowercase = False)vocabulary = count.fit_transform([words])print(count.get_feature_names())

例如,如果:

 words = "Hello @friend, this is a good day. #good."

我希望它被分隔成这样:

['Hello', '@friend', 'this', 'is', 'a', 'good', 'day', '#good']

目前,它被分隔成这样:

['Hello', 'friend', 'this', 'is', 'a', 'good', 'day']

回答:

你可以使用 CountVectorizer 中的 token_pattern 参数,如文档中所述:

传递一个正则表达式来告诉 CountVectorizer 什么应该被视为一个词。假设在这种情况下,我们告诉 CountVectorizer,即使包含 #@ 的词也应该被视为一个词。然后这样做:

count = CountVectorizer(lowercase = False, token_pattern = '[a-zA-Z0-9$&+,:;=?@#|<>.^*()%!-]+')

输出:

['#good', '@friend', 'Hello', 'a', 'day', 'good', 'is', 'this']

Related Posts

在使用k近邻算法时,有没有办法获取被使用的“邻居”?

我想找到一种方法来确定在我的knn算法中实际使用了哪些…

Theano在Google Colab上无法启用GPU支持

我在尝试使用Theano库训练一个模型。由于我的电脑内…

准确性评分似乎有误

这里是代码: from sklearn.metrics…

Keras Functional API: “错误检查输入时:期望input_1具有4个维度,但得到形状为(X, Y)的数组”

我在尝试使用Keras的fit_generator来训…

如何使用sklearn.datasets.make_classification在指定范围内生成合成数据?

我想为分类问题创建合成数据。我使用了sklearn.d…

如何处理预测时不在训练集中的标签

已关闭。 此问题与编程或软件开发无关。目前不接受回答。…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注