简体   繁体   English

如何将文本文件中的数据导入 Python 中的二维列表?

[英]How import data from a text file into 2D list in Python?

I was trying to make a random generator for DND Classes and Subclasses.我试图为 DND 类和子类制作一个随机生成器。 I tried making a text file that looks like this:我尝试制作一个看起来像这样的文本文件:

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

Normally I would code in the data into a list like this:通常我会将数据编码成这样的列表:

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

Is there anyway for it to read this data as say Barbarian Battle rager would be position (0,1) and bard glamour would be (1, 2)?无论如何,它是否可以读取此数据,例如野蛮人战斗狂怒者的位置(0,1)和吟游诗人的魅力(1, 2)? Or is there a better way to format the data so it can be put into this 2D list?或者有没有更好的方法来格式化数据,以便将其放入这个 2D 列表中? Thank you!谢谢!

First: you don't want a 2D list;第一:你不想要一个二维列表; you want a simple dictionary of strings to string lists.你想要一个简单的字符串字典到字符串列表。

Also, as suggested in the comments if your format is flexible, use JSON or XML rather than a flat text file.此外,如评论中所建议,如果您的格式灵活,请使用 JSON 或 XML 而不是纯文本文件。 If your format is not flexible, the following will do the trick:如果您的格式不灵活,以下方法可以解决问题:

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)

You can use JSON format to store this kind of data and directly import them into python list with the json library .您可以使用JSON格式存储此类数据,并使用json库将它们直接导入到python列表中。 I have taken the liberty to adjust your text file to a json file我冒昧地将您的文本文件调整为 json 文件

backgrounds.json:背景.json:

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

The python code:蟒蛇代码:

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

print(backgrounds)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM