【问题标题】:Separate config file and split the key collects in own file分离配置文件并拆分密钥收集在自己的文件中
【发布时间】:2019-08-02 12:15:51
【问题描述】:

这个插件有一个新的更新,所以所有的“任务”都必须放在一个单独的文件中。因为有超过 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

我所做的是遍历数据中的每个“任务”,这会创建一个位于“任务/任务/{任务名称}.yml”中的带有任务属性的“输出文件”。但是,我似乎可以让它工作,得到一个“字符串索引必须是整数”。

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()

遍历数据中的每个“任务”,这会创建一个位于“任务/任务/{questname}.yml”中的带有任务属性的“输出文件”。

【问题讨论】:

    标签: python file yaml config


    【解决方案1】:

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

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

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

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

    这是您脚本的修补版本:

    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()
    

    【讨论】:

    • 是的,这是因为您正在转储一个数组,我从您的示例中获取它并认为这很奇怪但自愿。在代码中进行了更改(yaml.dump 语句中没有括号)。
    猜你喜欢
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多