分离配置文件并将收集的密钥拆分到自己的文件中

Separate config file and split the key collects in own file

这个插件有一个新的更新,所以所有 "quests" 都必须在一个单独的文件中。因为有超过 100+ 我不想手动完成。旧文件 ("config.yml") 如下所示:"quests.{questname}.{attributes}" {attributes} 作为属于当前任务的每个键。新文件应以 {questname} 作为名称并在其中包含属性。这应该对所有文件完成。

config.yml(旧文件)

quests:
  farmingquest41:
    tasks:
      mining:
        type: "blockbreakcertain"
        amount: 100
        block: 39
    display:
      name: "&a&nFarming Quest:&r &e#41"
      lore-normal:
      - "&7This quest will require you to farm certain"
      - "&7resources before receiving the reward."
      - "&r"
      - "&6* &eObjective:&r &7Mine 100 brown mushrooms."
      - "&6* &eProgress:&r &7{mining:progress}/100 brown mushrooms."
      - "&6* &eReward:&r &a1,500 experience"
      - "&r"
      lore-started:
      - "&aYou have started this quest."
      type: "BROWN_MUSHROOM"
    rewards:
     - "xp give {player} 1500"
    options:
      category: "farming"
      requires:
       - ""
      repeatable: false
      cooldown:
        enabled: true
        time: 2880

我所做的是遍历数据中的每个 "quest",创建一个位于 "Quests/quests/{questname}.yml" 中的具有任务属性的 "outfile"。但是,我似乎可以让它工作,得到 "string indices must be integers".

import yaml

input = "Quests/config.yml"

def splitfile():
    try:
        with open(input, "r") as stream:
            data = yaml.load(stream)
            for quest in data:  
                outfile = open("Quests/quests/" + quest['quests'] + ".yml", "x")
                yaml.dump([quest], outfile)
    except yaml.YAMLError as out:
        print(out)

splitfile()

遍历数据中的每个 "quest",创建位于 "Quests/quests/{questname}.yml" 中的具有任务属性的 "outfile"。

错误来自 quest['quests']。您的数据是一本字典,其中一个条目名为 quests:

for quest in data:
  print(quest) # will just print "quests"

要在您的 yaml 中正确迭代,您需要:

  1. 获取任务字典,使用data["quests"]
  2. 对于任务字典中的每个条目,使用条目键作为文件名并将条目值转储到文件中。

这是您脚本的补丁版本:

def splitfile():
    try:
        with open(input, "r") as stream:
            data = yaml.load(stream)
            quests = data['quests'] # get the quests dictionary
            for name, quest in quests.items():  
                # .items() returns (key, value), 
                # here name and quest attributes
                outfile = open("Quests/quests/" + name + ".yml", "x")
                yaml.dump(quest, outfile)
    except yaml.YAMLError as out:
        print(out)

splitfile()