python-3.x 随机播放YAML文件中的内容

14ifxucb  于 2023-03-13  发布在  Python
关注(0)|答案(1)|浏览(160)

我有一个YAML文件,我有一个包含我想要 Shuffle 的字符串的列表:
列表:

['StmRsBgmSea02', 'StmRsBgmShopRadio', 'StmRsBgmSea01', ...]

这不是完整的列表。
YAML文件:

Version: 3
IsBigEndian: False
SupportPaths: False
HasReferenceNodes: False
root:
  StageInfoList:
    - Name: SeaWorldHomeStage
      StageScenarioInfoList:
        - ScenarioNo: !l 0
          StagePlayInfoList:
            - {Name: WorldMain, ResourceName: StmRsBgmSea02}
            - {Name: Shop, ResourceName: StmRsBgmShopRadio}
        - ScenarioNo: !l 1
          StagePlayInfoList:
            - {Name: WorldMain, ResourceName: StmRsBgmSea01}
            - {Name: Boss, ResourceName: StmRsBgmBossHaikai_B}
            - {Name: Town, ResourceName: StmRsBgmSea01beach}
            - {Name: BossDead, ResourceName: WsdRsBgmJgSeaFountain}
    - Name: SeaWorldCostumeStage
      StageScenarioInfoList:
        - ScenarioNo: !l 0
          StagePlayInfoList:
            - {Name: CostumeRoom, ResourceName: WsdRsBgmMarioPlayHula}

这个文件有800行,我有一个列表,上面有ResourceName:后面的所有名字。
我希望ResourceName:之后的每个值都被替换为列表中的一个随机值。重要的是,在一个RessourceName被随机化之后,该字符串将从列表中删除。这样就不会有任何值出现两次。

w8f9ii69

w8f9ii691#

当你从YAML(或JSON)加载数据时,你会得到一个容易递归的数据结构:所有的东西要么是一个字符串,要么是一个列表,要么是一个值,你应该做一个例程,在递归的时候沿着替换值的列表(这里是[v0, v1, v2, ...]),并且每当你找到一个名为ResourceName的键时就给它们赋值。

import sys
from pathlib import Path
import random
import ruamel.yaml

def recur(d, sub, key):
    if isinstance(d, dict):
        for k, v in d.items():
            if k == key:
                d[key] = selected = random.choice(sub)
                sub.remove(selected)
                continue
            recur(v, sub, key)
    elif isinstance(d, list):
        for elem in d:
            recur(elem, sub, key)
        

substitutes =['v0', 'v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v9']
    
yaml = ruamel.yaml.YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
data = yaml.load(Path('input.yaml'))
recur(data, substitutes, 'ResourceName')
yaml.dump(data, sys.stdout)

其给出:

Version: 3
IsBigEndian: false
SupportPaths: false
HasReferenceNodes: false
root:
  StageInfoList:
    - Name: SeaWorldHomeStage
      StageScenarioInfoList:
        - ScenarioNo: !l 0
          StagePlayInfoList:
            - {Name: WorldMain, ResourceName: v1}
            - {Name: Shop, ResourceName: v5}
        - ScenarioNo: !l 1
          StagePlayInfoList:
            - {Name: WorldMain, ResourceName: v2}
            - {Name: Boss, ResourceName: v0}
            - {Name: Town, ResourceName: v4}
            - {Name: BossDead, ResourceName: v3}
    - Name: SeaWorldCostumeStage
      StageScenarioInfoList:
        - ScenarioNo: !l 0
          StagePlayInfoList:
            - {Name: CostumeRoom, ResourceName: v7}

如果合适,您可能希望在调用recur()后检查替代项是否为空

相关问题