【发布时间】:2021-08-23 16:03:38
【问题描述】:
CountVectorizer 默认标记模式将下划线定义为字母
corpus = ['The rain in spain_stays' ]
vectorizer = CountVectorizer(token_pattern=r'(?u)\b\w\w+\b')
X = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names())
给予:
['in', 'rain', 'spain_stays', 'the']
这是有道理的,因为 AFAIK '/w' 等同于 [a-zA-z0-9_],我需要的是:
['in', 'rain', 'spain', 'stays', 'the']
所以我尝试用 [a-zA-Z0-9] 替换“/w”
vectorizer = CountVectorizer(token_pattern=r'(?u)\b[a-zA-Z0-9][a-zA-Z0-9]+\b')
X = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names())
但我明白了
['in', 'rain', 'the']
我怎样才能得到我需要的东西? 欢迎任何想法
【问题讨论】:
-
\w也匹配_所以这两个字符之间没有单词边界n_ -
那么我可以使用什么来代替 '/w' 来获得所需的结果?
-
没有单词边界,您可以使用例如
[^\W_]+regex101.com/r/zN3Oax/1 -
或者使用lookarounds形式的边界
(?:(?<=[\s_])|(?<=^))[^\W_]+(?=[\s_]|$)regex101.com/r/QaREpI/1 -
谢谢,工作。两者有区别吗?
标签: python regex scikit-learn countvectorizer