【问题标题】:Passing value in column as parameter in apply with nltk snowball stemmer使用 nltk 雪球词干分析器将列中的值作为参数传递
【发布时间】:2019-07-24 12:25:29
【问题描述】:

传递df[language] 适用于停用词,但不适用于雪球词干分析器。有没有办法解决这个问题?

到目前为止,我还没有真正找到任何线索......

import nltk
from nltk.corpus import stopwords
import pandas as pd
import re

df = pd.DataFrame([['A sentence in English', 'english'], ['En mening på svenska', 'swedish']], columns = ['text', 'language'])

def tokenize(text):
    tokens = re.split('\W+', text)
    return tokens

def remove_stopwords(tokenized_list, language):
    stopword = nltk.corpus.stopwords.words(language)
    text = [word for word in tokenized_list if word not in stopword]
    return text

def stemming(tokenized_text, l):
    ss = nltk.stem.SnowballStemmer(l)
    text = [ss.stem(word) for word in tokenized_text]
    return text

df['text_tokenized'] = df['text'].apply(lambda x: tokenize(x.lower()))
df['text_nostop'] = df['text_tokenized'].apply(lambda x: remove_stopwords(x, df['language']))
df['text_stemmed'] = df['text_nostop'].apply(lambda x: stemming(x, df['language']))

我希望它能够像去除停用词一样使用英语和瑞典语作为语言进行雪球词干提取。我收到error 消息如下:

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

【问题讨论】:

    标签: python nltk apply snowball


    【解决方案1】:

    试试这个。

    df['text_stemmed']=df.apply(lambda x: stemming(x['text_nostop'], x['language']), axis=1)
    

    编辑:当您在 df['text_tokenized'].apply(lambda x: ...) 等特定列上使用 apply 时,lambda 函数位于 x 上,即 text_tokenized 列的每一行,而 df['language'] 不适用于特定行,而是整个熊猫系列。

    也就是说,当你尝试lambda x: remove_stopwords(x, df['language'])时,df['language']的返回值不是对应行的某个“语言”值,而是一个包含“英语”和“瑞典语”的pandas系列。

    0    english
    1    swedish
    

    所以你的第二个代码apply 也应该更改:

    df['text_nostop'] = df.apply(lambda x: remove_stopwords(x['text_tokenized'], x['language']), axis=1)
    

    【讨论】:

    • 您能否为以后的读者添加一些解释,为什么您的代码可以解决问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    相关资源
    最近更新 更多