我在CSV转换方面遇到了麻烦,我不太确定如何做到这一点(不太熟悉CSV转换,把它作为一个附带项目进行测试),我有一个嵌套字典,我想要创建到CSV中:
我想在ITEM_ID
STRONG_AXE和FAST_AXE --另一个名为base的列,它包含攻击值10和1,与攻击速度相同。
10.0 0.1 0.1 0.2.
将所有这些(这是我的麻烦部分)转换成一个名为crit-power的列。
假设我有一个rpg的“axe.yml”:
# axe.yml
STRONG_AXE:
  base: iron_axe
  attack-damage: 10
  attack-speed: 1
  crit-power:
      base: 10.0
      scale: 0.1
      spread: 0.1
      maxSpread: 0.2
FAST_AXE:
  base: copper_axe
  attack-damage: 5
  attack-speed: 2现在我以f (file)的形式打开'axe.yml‘,然后将它转换为字典。
#writer.py
import csv,yaml 
with open(r'axe.yml') as f:
    dict_data = yaml.load(f, Loader=yaml.FullLoader)
    print (dict_data)然后出现的转换字典是:
{'STRONG_AXE': {'base': 'iron_axe', 'attack-damage': 10, 'attack-speed': 1, 'crit-power': {'base': 10.0, 'scale': 0.1, 'spread': 0.1, 'maxSpread': 0.2}}, 'FAST_AXE': {'base': 'copper_axe', 'attack-damage': 5, 'attack-speed': 2}}那么转换将如何工作呢?(删除了一段时间的编码,抱歉我.(新手)
发布于 2020-12-21 00:07:52
这里有一种处理嵌套数据的方法。它为嵌套字典中的每个项创建单独的字段,并在每个项的名称中添加一个前缀。
import csv
import yaml
from pprint import pprint
inp_filepath = 'axe.yml'
outp_filepath = 'axe.csv'
FAST, STRONG = 'FAST_AXE', 'STRONG_AXE'  # Axe type ids.
COMMON_FIELDS = ['base', 'attack-damage', 'attack-speed']
STRONG_AXE_ONLY_FIELDS = ['base', 'scale', 'spread', 'maxSpread']
CRIT_POWER_FIELDS = [('crit-power-' + fieldname) for fieldname in STRONG_AXE_ONLY_FIELDS]
CSV_FILE_FIELDS = ['axe-type'] + COMMON_FIELDS + CRIT_POWER_FIELDS
with open(inp_filepath) as file:
    data = yaml.load(file, Loader=yaml.FullLoader)
with open(outp_filepath, 'w', newline='') as file:
    writer = csv.DictWriter(file, CSV_FILE_FIELDS)
    writer.writeheader()
    for axetype, axedata in data.items():
        row = {'axe-type': axetype}
        if axetype == FAST:
            # Add common fields.
            row.update({fieldname: axedata[fieldname] for fieldname in COMMON_FIELDS})
        elif axetype == STRONG:
            # Add common fields.
            row.update({fieldname: axedata[fieldname] for fieldname in COMMON_FIELDS})
            # Then add renamed STRONG only fields.
            crit_power_data = axedata['crit-power']
            row.update({('crit-power-' + fieldname): crit_power_data[fieldname]
                            for fieldname in STRONG_AXE_ONLY_FIELDS})
        else:
            raise RuntimeError(f'unknown axe type "{axetype}" encountered')
#        pprint(row, sort_dicts=False)  # Show row data being written to file.
        writer.writerow(row)
print('Conversion completed')下面是pprint()调用的一些示例输出,其中显示正在创建的带有前缀字段名键的row字典:
{'axe-type': 'STRONG_AXE',
 'base': 'iron_axe',
 'attack-damage': 10,
 'attack-speed': 1,
 'crit-power-base': 10.0,
 'crit-power-scale': 0.1,
 'crit-power-spread': 0.1,
 'crit-power-maxSpread': 0.2}
{'axe-type': 'FAST_AXE',
 'base': 'copper_axe',
 'attack-damage': 5,
 'attack-speed': 2}https://stackoverflow.com/questions/64946826
复制相似问题