Skip to main content
 首页 » 编程设计

Python 解析包含函数、列表和字典的字符串

2024年10月17日24luoye11

我正在尝试寻找方法来解析可以包含变量、函数、列表或用“,”分隔的 python 语法编写的字典的字符串。空格应该在任何地方都可用,所以当它不在 ()、[] 或 {} 内时,用 ","分隔。

示例字符串:"variable, function1(1,3), function2([1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"}"

另一个字符串示例:"variable,function1(1, 3) , function2( [1,3],2), ['list_item_1','list_item_2'],{'dict_key_1': "dict_item_1"} "

示例输出 ["variable", "function1(1,3)", "function2([1,3],2)", "['list_item_1','list_item_2']", "{' dict_key_1': "dict_item_1"}"]

编辑: 该代码的原因是解析字符串,然后使用 exec("var = &s"% list[x]) 运行它。 (是的,我知道这可能不是推荐的做事方式)

请您参考如下方法:

我想这里的主要问题是数组和字典中也有逗号,所以只使用 str.split(",") 是行不通的。一种方法是一次解析字符串一个字符,并跟踪是否所有括号都已关闭。如果是,我们可以在遇到逗号时将当前结果追加到数组中。这是我的尝试:

s = "variable, function1(1,3),function2([1,3],2),['list_item_1','list_item_2'],{'dict_key_1': 'dict_item_1'}" 
 
tokens = [] 
current = "" 
open_brackets = 0 
 
for char in s: 
    current += char 
 
    if char in "({[": 
        open_brackets += 1 
    elif char in ")}]": 
        open_brackets -= 1 
    elif (char == ",") and (open_brackets == 0): 
        tokens.append(current[:-1].strip()) 
        current = "" 
 
tokens.append(current) 
 
for t in tokens: 
    print(t) 
 
""" 
    variable 
    function1(1,3) 
    function2([1,3],2) 
    ['list_item_1','list_item_2'] 
    {'dict_key_1': 'dict_item_1'} 
"""