首页 > 解决方案 > python中函数内部的参数

问题描述

我正在尝试解决有关参数的两个函数的问题。具体来说,我有以下问题:

def remove_stopwords(text):
list_words=[]
stop_words = (stopwords.words('italian'))
                  
#bla bla bla
return(' '.join(t))

def clean(file):


# bla bla bla
file['C'] = file['Text'].apply(remove_stopwords())
# bla bla bla
return

然后当我按如下方式调用函数时:

clean(df)

它运作良好。但是,我想做这样的事情:

language='italian' 
clean(df, language)

其中语言应该是放置在这里的字符串:

def remove_stopwords(text):

    list_words=[]
    stop_words = (stopwords.words(str(language)) # <--
...

问题是这个函数在 clean() 里面,当我尝试运行它时,我得到一个关于参数的错误。

您能告诉我如何在上述函数中正确编写参数吗?

标签: pythonpandas

解决方案


我相信 lambda 函数会做你正在尝试的事情。像这样的东西:

def remove_stopwords(text, language):
    list_words=[]
    stop_words = (stopwords.words(language))               
    return(' '.join(t))

def clean(file, language):
    file['C'] = file['Text'].apply(lambda x: remove_stopwords(x, language))
    return file['C']

clean(file, 'italian')

推荐阅读