解析字符串中函数的参数

2024-09-26 15:28:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是一个代码的初学者,所以我不知道我是否在问一个愚蠢的问题,甚至可能会误用一些术语

我的问题是python中有一个字符串,其中包含一个可以理解为函数的文本,我想在列表中提取他的参数

字符串的示例:

line = """State("boatsmith search", "Search for the holder of the golden compass", delay=6)"""

作为处理该字符串的结果,我希望:

["boatsmith search", "Search for the holder of the golden compass", "delay=6"]

我不知道我说的是否清楚

我要找的东西是:

line = """State("boatsmith search", "Search for the holder of the golden compass", delay=6)"""

def function(x)
    # magic with x
    return list() # a list type result not actualy a list() xD

function(line)
>> ["boatsmith search", "Search for the holder of the golden compass", "delay=6)"]

事先非常感谢


Tags: ofthe字符串forsearchcompasslinefunction
3条回答

您可以在下面尝试:

line = """State("boatsmith search", "Search for the holder of the golden compass", delay=6)"""

def function(x)
    start = x.find("(") + len("(")
    end = x.find(")")
    substring = x[start:end]
    print(substring.replace('"', '').split(','))

您可以使用ast模块解决此问题。它有ast.NodeVisitor,这是一个基类,它遍历抽象语法树,并为找到的每个节点调用访问者函数

>>> line = """State("boatsmith search", "Search for the holder of the golden compass", delay=6)"""
>>> import ast
>>> tree = ast.parse(line)
>>> args = []
>>>
>>> class VisitCall(ast.NodeVisitor):
...     def visit_Call(self, node):
...         for i in node.args + node.keywords:
...             if isinstance(i, ast.Constant):
...                 args.append(i.value)
...             if isinstance(i, ast.keyword):
...                 args.append(f"{i.arg}={i.value.value}")
...
>>> visitor = VisitCall()
>>> visitor.visit(tree)
>>> print(args)
['boatsmith search', 'Search for the holder of the golden compass', 'delay=6']

您可以在visit_Call方法中处理不同的条件

可以使用正则表达式:

import re

re.search('\((.*)\)', line.replace('"', '')).group(1).split(', ')

输出:

['boatsmith search', 'Search for the holder of the golden compass', 'delay=6']

the string could be written with double quotes or with single quotes

在这种情况下,您可以使用:

line = """State("boatsmith search", 'Search for the holder of the golden compass', delay=6)"""

[e.strip('"\'') for e in re.search('\((.*)\)', line).group(1).split(', ')]

输出:

['boatsmith search', 'Search for the holder of the golden compass', 'delay=6']

相关问题 更多 >

    热门问题