将表达式分配给变量并在另一个函数中使用



我得到了以下代码,该代码应在另一个函数中使用,因此我想使用变量

将其传递给它
soup.find("div", {"class" : "article-entry text"}).text.replace('n', "")

使用

textFormat = "soup.find("div", {"class" : "article-entry text"}).text.replace('n', "")"

显然不起作用。我必须逃脱角色吗?如何?

执行TextFormat内容的最佳方法是什么。喜欢吗?

text = exec(textFormat)

谢谢!

使用lambda:

soup_find = lambda x,y: soup.find(x,y).text.replace('n', '')
soup_find("div", {"class" : "article-entry text"})

您可以将其包装在这样的另一个函数中:

def textFormat():
    return soup.find("div", {"class" : "article-entry text"}).text.replace('n', "")

然后这样使用:

text = textFormat()

如果要将其传递给另一个功能:

def func(another_func):
    return another_func()
func(textFormat)

您需要逃脱字符串被包围的引号。此外,您需要使用原始字符串来逃脱其他字符。所以...:

textFormat = r'soup.find("div", {"class" : "article-entry text"}).text.replace('n', "")' 

但是,如果您需要应用具有部分固定元素的函数,则应仅使用 functools partial,而不是使用eval的临时。使用部分您可以修复常见参数并通过每个呼叫中并非常见的其他参数。

最新更新