【问题标题】:sklearn - how to use TfidfVectorizer to use entire strings?sklearn - 如何使用 TfidfVectorizer 使用整个字符串?
【发布时间】:2014-07-18 03:48:11
【问题描述】:

我在使用数据集中所有 URL 的主机名作为特征时遇到了这个问题。我无法弄清楚如何使用 TfidfVectorizer 仅从 URL 中提取主机名并计算它们的权重。 例如,我有一个数据框 df,其中“url”列包含我需要的所有 URL。我想我必须这样做:

def preprocess(t):
    return urlparse(t).hostname

tfv = TfidfVectorizer(preprocessor=preprocess)

tfv.fit_transform([t for t in df['url']])

这种方式似乎不起作用,因为它拆分主机名而不是将它们视为整个字符串。我认为这与analyzer='word'(默认情况下)有关,它将字符串拆分为单词。

任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: python nlp preprocessor scikit-learn


    【解决方案1】:

    你是对的。 analyzer=word 创建一个使用默认标记模式'(?u)\b\w\w+\b' 的标记器。如果您想将整个 URL 标记为单个标记,您可以更改标记模式:

    vect = CountVectorizer(token_pattern='\S+')
    

    这会将https://www.pythex.org hello hello.there 标记为['https://www.pythex.org', 'hello', 'hello.there']。然后,您可以创建一个分析器以从 URL 中提取主机名,如 this question 所示。您可以扩展 CountVectorizer 以更改其 build_analyzer 方法,或者只是对其进行修补:

    def my_analyser():
        # magic is a function that extracts hostname from URL, among other things
        return lambda doc: magic(preprocess(self.decode(doc)))
    
    vect = CountVectorizer(token_pattern='\S+')
    vect. build_analyzer = my_analyser
    vect.fit_transform(...)
    

    注意:标记化并不像看起来那么简单。我使用的正则表达式有很多限制,例如如果句号后没有空格,它不会拆分句子的最后一个标记和下一个句子的第一个标记。一般来说,正则表达式标记器很快就会变得非常笨拙。我建议查看nltk,它提供了几种不同的非正则表达式标记器。

    【讨论】:

      猜你喜欢
      • 2013-12-06
      • 2019-12-27
      • 2020-02-17
      • 2017-04-27
      • 2018-07-18
      • 2022-01-14
      • 2013-02-14
      • 2017-06-07
      • 1970-01-01
      相关资源
      最近更新 更多