【问题标题】:'first argument must be string or compiled pattern' error in tf-idf vectorizertf-idf 矢量化器中的“第一个参数必须是字符串或编译模式”错误
【发布时间】:2021-12-17 07:35:18
【问题描述】:

dfff 是一个已经被标记化的数据帧,将用于通过 tfidfvectorizer 转换为 tf-idf。

这是 dfff 示例:

[![在此处输入图片描述][1]][1]

然后我创建一个 tfidfvectorizer 一个

tfidf_vecer2 = TfidfVectorizer(analyzer = 'word', token_pattern=None)

然后我运行了这段代码:

tfidf_vectorr= tfidf_vecer2.fit_transform(dfff)
tfidf_array = np.array(tfidf_vectorr.todense())

突然,TypeError 作为输出发生了,我仍然无法弄清楚。 我尝试使用列表而不是数据框,但它仍然出错。这是一个输出:

TypeError: 第一个参数必须是字符串或编译模式

【问题讨论】:

    标签: python scikit-learn nlp tf-idf tfidfvectorizer


    【解决方案1】:

    看不到您的示例数据框,但我们假设它是这样的:

    import nltk
    
    df = pd.DataFrame({'text':["Though worlds of wanwood leafmeal lie",
    "And yet you will weep and know why"]})
    df['tokenized'] = df['text'].apply(nltk.word_tokenize)
    
                                        text                                     tokenized
    0  Though worlds of wanwood leafmeal lie  [Though, worlds, of, wanwood, leafmeal, lie]
    1     And yet you will weep and know why   [And, yet, you, will, weep, and, know, why]
    

    然后你需要一个虚拟函数用作标记器,以便保持输入不变:

    def func(x):
        return x
    
    tfidf_vec = TfidfVectorizer(tokenizer=func,analyzer='word',
    preprocessor=func,token_pattern=None)
    
    tfidf_vec.fit(df['tokenized'])
    

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 2018-02-07
      • 1970-01-01
      • 2023-03-17
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多