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

2024-04-29 06:38:45 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将预处理器传递给TfidfVectorizer? 我做了一个函数,它接受一个字符串并返回一个经过预处理的字符串 然后我将处理器参数设置为函数“preprocessor=preprocess”,但它不起作用。 我找了这么多次,但没有找到一个例子,好像没人用似的。

我还有一个问题。 它(预处理器参数)是否覆盖了可以使用停止字和小写参数完成的删除停止字和小写大小写的操作?


Tags: 函数字符串参数处理器例子小写preprocessorpreprocess
1条回答
网友
1楼 · 发布于 2024-04-29 06:38:45

您只需定义一个函数,它接受一个字符串作为输入并重新运行要预处理的内容。例如,一个简单的大写字符串函数如下所示:

def preProcess(s):
    return s.upper()

一旦创建了函数,就只需将其传递到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()

结果:

[u'AND', u'DOCUMENT', u'FIRST', u'IS', u'ONE', u'SECOND', u'THE', u'THIRD', u'THIS']

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

preprocessor : callable or None (default) Override the preprocessing (string transformation) stage while preserving the tokenizing and n-grams generation steps.

相关问题 更多 >