如何在CountVectorizer的词汇表中使用正则表达式?

时间:2018-07-16 01:41:56

标签: python scikit-learn nlp text-classification countvectorizer

如何使“文档中的第一个单词是[目标单词]”成为一项功能?

考虑以下两个句子:

example = ["At the moment, my girlfriend is Jenny. She is working as an artist at the moment.",
       "My girlfriend is Susie. She is working as an accountant at the moment."]

如果我要衡量关系承诺,我希望能够将“此刻”一词当初出现时仅作为 功能。< / p>

我会喜欢能够在词汇表中使用正则表达式...

phrases = ["^at the moment", 'work']
vect = CountVectorizer(vocabulary=phrases, ngram_range=(1, 3), token_pattern=r'\w{1,}')
dtm = vect.fit_transform(example)

但这似乎不起作用。

我也尝试过这种方法,但是出现“词汇是空的”错误...

CountVectorizer(token_pattern = r"(?u)^currently")

什么是正确的方法?我需要自定义矢量化程序吗?您可以将我链接到任何简单的教程吗?这是我的第一个sklearn项目,并且我已经在谷歌上搜索了几个小时。任何帮助,不胜感激!

1 个答案:

答案 0 :(得分:0)

好的,我想我已经找到了一种方法,该方法基于对本教程中的get_tweet_length()函数进行破解... https://ryan-cranfill.github.io/sentiment-pipeline-sklearn-4/

我添加了此功能...

def first_words(text):
    matchesList = re.findall('^at the moment', text, re.I)
    if len(matchesList) > 0:
        return 1
    else:
        return 0

并将它们与基本的sklearn_helper pipelinize_feature()函数一起使用,该函数将输出转换为sklearn的FeautreUnion函数所需的数组格式。

vect4 = pipelinize_feature(first_words, active=True)

然后我可以通过FeatureUnion与正常的CountVectorizers一起使用

unionObj = FeatureUnion([
        ('vect1', vect1),
        ('vect2', vect2),
        ('vect4', vect4)
])