使用 python 函数从字符串中提取参数

Extract arguments from string with python function

我正在寻找一种方法来提取作为字符串返回给我的 python 函数中嵌入的参数。

例如:

'create.copy("Node_A", "Information", False)'
# expected return: ["Node_A", "Information", "False"]

'create.new("Node_B")'
# expected return: ["Node_B"]

'delete("Node_C")'
# expected return: ["Node_C"]

我的第一个方法是像这样的正则表达式:

re.match(r"("(.+?")")

但它一直 returns None。

我怎样才能得到这个参数的列表?

顺便说一句:我被迫使用 Python 2.7 并且只使用内置函数 :(

您可以使用内置的 ast 模块解析这些表达式。

import ast

def get_args(expr):
    tree = ast.parse(expr)
    args = tree.body[0].value.args
    
    return [arg.value for arg in args]

get_args('create.copy("Node_A", "Information", False)') # ['Node_A', 'Information', False]
get_args('create.new("Node_B")') # ['Node_B']
get_args('delete("Node_C")') # ['Node_C']

见下文(使用 python 3.6 测试)

def get_args(expr):
    args = expr[expr.find('(') + 1:expr.find(')')].split(',')
    return [x.replace('"', '') for x in args]


entries = ['create.copy("Node_A", "Information", False)', "create.new(\"Node_B\")"]
for entry in entries:
    print(get_args(entry))

输出

   ['Node_A', ' Information', ' False']
   ['Node_B']

这里是一个没有任何外部模块并且完全兼容 python2.7 的例子。对字符串 w.r.t 进行切片。括号的位置,清除多余的空白并在 ,.

处拆分
f = 'create.copy("Node_A", "Information", False)'
i_open = f.find('(')
i_close = f.find(')')

print(f[i_open+1: i_close].replace(' ', '').split(','))

输出

['"Node_A"', '"Information"', 'False']

备注:

  • 不适用于嵌套函数。

  • 也可以通过反转字符串找到右括号

    i_close = len(f) - f[::-1].find(')') - 1