gpt4 book ai didi

python - CountVectorizer token_pattern 不捕捉下划线

转载 作者:行者123 更新时间:2023-12-04 07:33:23 25 4
gpt4 key购买 nike

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']
我怎样才能得到我需要的东西?
欢迎任何想法

最佳答案

n_之间没有词界如 \w也匹配下划线。
要匹配 2 个或更多没有下划线的单词字符,并且只允许左右有空白边界或下划线:

(?<![^\s_])[^\W_]{2,}(?![^\s_])
模式匹配:
  • (?<![^\s_])负向后视,在左边断言空白边界或下划线
  • [^\W_]{2,}匹配单词字符 2 次或多次,不包括下划线
  • (?![^\s_])负前瞻,在右侧断言空白边界或下划线

  • regex demo .

    非常广泛的匹配可能是 [^\W_]{2,}但请注意,这并没有考虑到边界。它只匹配没有下划线的单词字符。
    查看此 regex demo 中不同数量的匹配项.

    关于python - CountVectorizer token_pattern 不捕捉下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67856904/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com