gpt4 book ai didi

python - python 中 TfidfVectorizer 中 n-gram 的标记模式

转载 作者:太空狗 更新时间:2023-10-30 00:17:14 25 4
gpt4 key购买 nike

TfidfVectorizer 是否使用 python 识别 n-gram regular expressions

阅读 scikit-learn TfidfVectorizer 的文档时出现此问题,我看到在单词级别识别 n-gram 的模式是 token_pattern=u'(?u)\b\w\w+\b'。我无法理解这是如何工作的。考虑二元语法的情况。如果我这样做:

    In [1]: import re
In [2]: re.findall(u'(?u)\b\w\w+\b',u'this is a sentence! this is another one.')
Out[2]: []

我没有找到任何双字母组。鉴于:

    In [2]: re.findall(u'(?u)\w+ \w*',u'this is a sentence! this is another one.')
Out[2]: [u'this is', u'a sentence', u'this is', u'another one']

找到一些(但不是全部,例如 u'is a' 和所有其他偶数双字母组都丢失了)。我在解释 \b 字符函数时做错了什么?

注意:根据正则表达式模块文档,re 中的 \b 字符应该:

\b Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character.

我看到一些问题解决了在 python 中识别 n-gram 的问题(参见 12),所以第二个问题是:我应该这样做并在将我的文本提供给 TfidfVectorizer 之前添加连接的 n-gram 吗?

最佳答案

您应该在正则表达式前加上 r。以下作品:

>>> re.findall(r'(?u)\b\w\w+\b',u'this is a sentence! this is another one.')
[u'this', u'is', u'sentence', u'this', u'is', u'another', u'one']

这是一个 known bug in the documentation , 但如果你看看 source code他们确实使用原始文字。

关于python - python 中 TfidfVectorizer 中 n-gram 的标记模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29290955/

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