0

我有以下字典:

config = {
'base_dir': Path(__file__).resolve(strict=True).parent.absolute(),
'app_dir': '<base_dir>/app'
}

我想替换<base_dir>为的值,<base_dir> 所以我这样做了:

for key, value in config.items():
    if type(value) == str:
        vars_to_replace = re.findall(r'\<.+\>',value)
        for var in vars_to_replace:
            config[key] = value.replace(var,config[var[1:-1]])

目前收到错误:TypeError: replace() argument 2 must be str, not WindowsPath

如果我config[var[1:-1]]str(). 它消除了错误,但我丢失了 WindowsPath,现在 app_dir 变成了一个字符串。我想将对象保留为 WindowsPath。

4

2 回答 2

0

我会说两者都提取base_dirapp然后用它们构建一条路径:

for key, value in config.items():
    if isinstance(value, str):
        # parent_str will be "base_dir" and name_str will be "app"
        parent_str, name_str = re.fullmatch(r"\<(.+)?>/(\w+)", value).groups()
        parent_path = config[parent_str]
        config[key] = parent_path / Path(name_str)

我没有使用 for 循环,假设一个值中只有一个这样的匹配是可能的。如果不是这种情况,您可以用finditer.

于 2020-05-31T19:40:06.870 回答
0

value是一个字符串,因此您尝试使用字符串的replace方法,该方法将两个字符串作为参数。如果要将 的值更改为app_dirPath 对象,则必须构造一个路径对象并将当前值('/app')替换为该对象。您可以通过多种方式执行此操作,这是一种:

  • 将 base_dir 转换为字符串,将其中的标记替换app_dir为该字符串,然后将新路径转换为 ​​Path 对象

这看起来像:

for key, value in config.items():
    if type(value) == str:
        vars_to_replace = re.findall(r'\<*[.+]\>',value)
        for var in vars_to_replace:
            new_path = value.replace(var, str(config[var[1:-1]]))
            config[key] = Path(new_path)

另一种方法是使用类似于path.join()附加到路径对象的东西:

path_addition = value.replace(var, "")
new_path_object = config[var].join(path_addition) # <-- might need to adjust this depending on the exact Path class you are using
config[key] = new_path_object

希望这些帮助,快乐编码!

于 2020-05-31T19:35:28.180 回答