如何修改 Python 脚本以从 JSON 模板中的不同路径结构中提取标识符

问题描述 投票:0回答:1

我有一个 Python 脚本,可以根据 JSON 模板生成映射 JSON。

脚本读取 JSON 模板,然后比较必须与模板匹配的文件夹结构,以便它可以输出具有相应值的新 JSON。

这是 JSON 模板中的一行示例。

"path_structure": "Folder/Apples/{apple_ids}/*",

然后,脚本将收到如下所示的文件夹结构:

Folder/
└── Apples/
    ├── 43952/
    ├── 53453/
    ├── 12342/
    └── 76552/

脚本中生成的单独 JSON 将包含以下行:

"value": "43952"

"value": "53453"

"value": "12342"

"value": "76552"

脚本现在看起来像这样。


def get_relative_path(file, start_dir):
  relative_path = os.path.relpath(file, start=start_dir)
  return os.path.normpath(relative_path).split(os.sep)

file_components = get_relative_path(file, start_dir)

def get_path_components(mapping_file_json):
  path_structure = mapping_file_json["path_structure"].rstrip("/*")
  return path_structure.split("/")

path_components = get_path_components(mapping_file_json)

def get_linking_identifier(path_components):
  linking_identifiers = ["{apple_ids}"]

  for linking_identifier in linking_identifiers:
    try:
      linking_identifier_index = path_components.index(linking_identifier)
      return linking_identifier_index
    except ValueError:
      continue

value = file_components[linking_identifier_index]

"value": str(value)

我的询问是关于支持更改模板结构。

我需要支持 JSON 模板可能如下所示:

"path_structure": "Folder/Apples/notimportant_{apple_ids}/*"

"path_structure": "Folder/Apples/{apple_ids}_random/*"

"path_structure": "Folder/Apples/random{apple_ids}words/*"

文件夹结构示例:

Folder/
└── Apples/
    ├── notimportant_43952/
    ├── notimportant_53453/
    ├── notimportant_12342/
    └── notimportant_76552/

Folder/
└── Apples/
    ├── 43952_random/
    ├── 53453_random/
    ├── 12342_random/
    └── 76552_random/

输出的搜索值仍应如下所示:

"value": "43952"

"value": "53453"

"value": "12342"

"value": "76552"

如何最好地编辑我的脚本以支持此新功能?

python json
1个回答
0
投票

我想你可以清理最终值:

import re
value = """
Folder/
└── Apples/
    ├── notimportant_43952/
    ├── notimportant_53453/
    ├── notimportant_12342/
    └── notimportant_76552/
or

Folder/
└── Apples/
    ├── 43952_random/
    ├── 53453_random/
    ├── 12342_random/
    └── 76552_random/
"""


clean_value = re.findall(r"(?<=_)[0-9]{5}(?=\/)|[0-9]{5}(?=_)", value)
print(clean_value)
# print(clean_value[0])


© www.soinside.com 2019 - 2024. All rights reserved.