【问题标题】:[Python]How to edit nested array config values with recursion[Python]如何使用递归编辑嵌套数组配置值
【发布时间】:2018-10-29 12:46:19
【问题描述】:

我有一个由多个嵌套数组和字典组成的配置文件。我需要一个可以编辑任何变量的文本命令。这是在 Python 3 中。

这是一个配置示例(json):

{
    "joinMsg":{    
        "help":[
            "I need help",
            "Type !help or !info"
        ]
}

命令语法可以更改为其他内容,但如下:

!config write joinMsg;help;1 'Try typing !help'

我想出了如何以这种方式从配置中读取,但我设置递归的方式意味着我没有办法替换该值。

这就是我所拥有的,数组类似于 joinMsg;help;1 with ;分隔符:

# reads from the config file
def configRead(arrays):
    try:
        arrays = configSearch(arrays)
        print(arrays)
        output = config
        for r in arrays:
            output = output[r]
    except:
        output = 'No array found'
    return output

# recursive config helper
def configSearch(arrays):
    searchRE = re.match(r'([^;]+);(.+)', arrays, re.I)
    if searchRE:
        output = configSearch(searchRE.group(2))
        output.insert(0, searchRE.group(1))
        return output
    else:
        return [arrays]

这段代码可能很糟糕(我没有受过正式培训),我不知道从这里做什么。任何帮助表示赞赏,谢谢。

【问题讨论】:

  • 您尝试递归执行此操作是否有特定原因?如果需要的话,先迭代然后再递归可能会更容易。
  • 不,它不必是递归的,这只是我能想到的唯一方法。你有什么建议?
  • 我会把它放在一个 while 或 for 循环中并循环遍历我的数组,直到找到正确的值,然后用新值替换该索引处的值。就像当前索引 != 数组的末尾继续查找一样。当当前索引 == 您要查找的索引时,只需将新值插入该索引即可覆盖旧值。我没有在 python 中与 JSON 进行太多交互,所以这可能不是很有帮助,如果我遇到类似的问题,我会这样做。
  • 这几乎就是我对for r in arrays: 所做的,一旦我让递归构建了一个数组名称数组。问题是我可以获得值但路径丢失,除非我从底部递归重建数组...

标签: python json regex recursion config


【解决方案1】:

首先,这是一个修改后的configSearch,它不使用递归并且还处理数组索引:

def configSearch(arrays):
    arrays = arrays.split(";")
    return [int(a) if a.isdigit() else a for a in arrays]

这里有一个新函数configWrite,它将编辑配置配置并用新的value覆盖arrays

def configWrite(arrays, value):
    arrays = configSearch(arrays)
    print(arrays)
    output = config
    for r in arrays[:-1]:
        output = output[r]
    output[arrays[-1]] = value

【讨论】:

    猜你喜欢
    • 2016-02-16
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多