Parse txt to blocks

前端 未结 5 1219
时光说笑
时光说笑 2021-01-26 17:56

i have a txt file, which has the following structure

start
id=1
date=21.05.2018
summ=500
end

start
id=7
date=23.05.2018
summ=500
owner=guest
end
5条回答
  •  梦毁少年i
    2021-01-26 18:11

    Using Regex.

    import re
    
    with open(filename, "r") as infile:
        data = infile.read()
        data = re.findall("(?<=\\bstart\\b).*?(?=\\bend\\b)", data, flags=re.DOTALL)   #Find the required data from text
    
    r = []
    for i in data:
        val =  filter(None, i.split("\n"))
        d = {}
        for j in val:
            s = j.split("=")    #Split by "=" to form key-value pair
            d[s[0]] = s[1]
        r.append(d)             #Append to list
    print(r)
    

    Output:

    [{'date': '21.05.2018', 'summ': '500', 'id': '1'}, {'date': '23.05.2018', 'owner': 'guest', 'summ': '500', 'id': '7'}]
    

提交回复
热议问题