如何将预处理器传递给TfidfVectorizer? - sklearn - python

ema*_*man 11 python preprocessor scikit-learn

如何将预处理器传递给TfidfVectorizer?我创建了一个函数,它接受一个字符串并返回一个预处理的字符串,然后我将处理器参数设置为该函数"preprocessor = preprocess",但它不起作用.我搜索了很多次,但我没有找到任何例子,好像没有人使用它.

我有另一个问题.它(预处理器参数)是否覆盖了删除停用词以及可以使用stop_words和小写参数完成的低级情况?

Dav*_*vid 23

您只需定义一个函数,该函数将字符串作为输入并返回要预处理的内容.因此,例如对大写字符串的简单函数将如下所示:

def preProcess(s):
    return s.upper()
Run Code Online (Sandbox Code Playgroud)

完成功能后,只需将其传递给TfidfVectorizer对象即可.例如:

from sklearn.feature_extraction.text import TfidfVectorizer

corpus = [
     'This is the first document.',
     'This is the second second document.',
     'And the third one.',
     'Is this the first document?'
     ]

X = TfidfVectorizer(preprocessor=preProcess)
X.fit(corpus)
X.get_feature_names()
Run Code Online (Sandbox Code Playgroud)

结果是:

[u'AND', u'DOCUMENT', u'FIRST', u'IS', u'ONE', u'SECOND', u'THE', u'THIRD', u'THIS']
Run Code Online (Sandbox Code Playgroud)

这会间接回答您的后续问题,因为尽管将小写设置为true,但是将大写的预处理函数覆盖它.文档中也提到了这一点:

预处理程序:可调用或无(默认)覆盖预处理(字符串转换)阶段,同时保留标记化和n-gram生成步骤.