python中TfidfVectorizer中n-gram的令牌模式

时间:2015-03-26 23:51:45

标签: python regex scikit-learn n-gram

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

在阅读scikit-learn TfidfVectorizer的文档时出现了这个问题,我发现在单词级别识别n-gram的模式是token_pattern=u'(?u)\b\w\w+\b'。我很难看到它是如何工作的。考虑bi-gram案例。如果我这样做:

    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匹配空字符串,但仅匹配单词的开头或结尾。单词被定义为字母数字或下划线字符的序列,因此单词的结尾由空格或非字母数字的非下划线字符表示。

我看到了解决在python中识别n-gram问题的问题(参见12),所以第二个问题是:我应该这样做并添加连接的n-gram然后再喂我的文字到TfidfVectorizer?

1 个答案:

答案 0 :(得分:1)

您应该使用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,他们会使用原始文字。