如何在Python中将数据从文本文件导入到2D列表中?

2024-06-07 06:53:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为DND类和子类创建一个随机生成器。我尝试制作一个如下所示的文本文件:

Barbarian
  Ancestral Guardian
  Battle Rager
  Beast
  Berserker
  Storm Herald
  Totem Warrior
  Wild Magic
  Zealot
Bard
  Creation
  Eloquence
  Glamour
  Lore
  Spirits
  Swords
  Valor
  Whispers

通常,我会将数据编码到如下列表中:

backgrounds = {}
with open("./Data/backgrounds.txt") as text:
  backgrounds = text.readlines()
text.close()

不管怎样,它是否可以将这些数据解读为“野蛮人战斗狂人”的位置(0,1),而“吟游诗人魅力”的位置(1,2)? 或者是否有更好的方式格式化数据,以便将其放入此2D列表中?谢谢大家!


Tags: 数据text列表子类berserker文本文件stormguardian
2条回答

第一:你不想要一个2D列表;您需要一个简单的字符串字典来创建字符串列表

此外,如评论中所建议的,如果您的格式灵活,请使用JSON或XML,而不是平面文本文件。如果您的格式不灵活,以下方法可以解决此问题:

from pprint import pprint
from typing import Dict, List

classes: Dict[str, List[str]] = {}

with open('./Data/classes.txt') as f:
    for line in f:
        if line.startswith(' '):
            current_classes.append(line.strip())
        else:
            current_classes = classes.setdefault(line.rstrip(), [])


pprint(skills)

您可以使用^{}格式存储此类数据,并使用json library将它们直接导入python列表。我已经自由地将您的文本文件调整为json文件

backgrounds.json:

{
    "Barbarian":["Ancestral Guardian","Battle Rager","Beast","Berserker","Storm Herald","Totem Warrior","Wild Magic",""],
    "Bard":["Creation","Eloquence","Glamour","Lore","Spirits","Swords","Valor"," Whispers"]
}

python代码:

import json
with open('backgrounds.json','r') as file:
    backgrounds = json.load(file)

print(backgrounds)

相关问题 更多 >