Home > front end >  How to get nested data from a file?
How to get nested data from a file?

Time:04-10

I have a text file named database.txt that looks like this:

samuel:
  term1:
    science = 50
    math = 60
  term2:
    science = 51
    math = 61
  term3:
    science = 52
    math = 62
  term4:
    science = 53
    math = 63

Now I want to convert the data into variables, something like this, the question is how?

name = str(input(Input name: ))

with open('database.txt', 'r') as database:
    database_contents = database.read(name)
    class grades:
        science1 = ""
        math1 = ""
        science2 = ""
        math2 = ""
        science3 = ""
        math3 = ""
        science4 = ""
        math4 = ""

print(grades)????

CodePudding user response:

import re

name = input("Input name: ")
grades = {}
with open("database.txt") as file:
    lines = list(map(lambda x: x[:-1], file.readlines()))
    start = lines.index(name   ":")   1
    end = list(map(lambda x: re.match(r"^[^:\s] :", x) is not None,lines[start:])).index(True)   start
    for line in map(lambda x: x.strip(), lines[start: end]):
        if re.match(r"term[0-9] :", line) is not None:
            index = line[4:-1]
        else:
            name, grade = line.split(" = ")
            grades[name   index] = int(grade)
    print(grades)

because nobody sent answer, I send a quick and semi-advanced answer and hope can be helpful... you must know about map function and regex

CodePudding user response:

Since your format is close enough to YAML, you may do some small mods to handle that. Of course, if you have the choice, as @jonrsharpe said in the comments, then use the proper format to start with.

txt = """samuel:
  term1:
    science = 50
    math = 60
  term2:
    science = 51
    math = 61
  term3:
    science = 52
    math = 62
  term4:
    science = 53
    math = 63
"""

d = yaml.safe_load(re.sub('\s*=', ':', txt))

>>> d
{'samuel': {'term1': {'science': 50, 'math': 60},
  'term2': {'science': 51, 'math': 61},
  'term3': {'science': 52, 'math': 62},
  'term4': {'science': 53, 'math': 63}}}

Since the data is in a file, you may first slurp it all in a string:

with open(filename) as f:
    txt = f.read()

# then
d = yaml.safe_load(re.sub('\s*=', ':', txt))
  • Related