Last active
October 22, 2019 15:17
-
-
Save nobbynobbs/dbffb4cf5f78acfc07e950a964ae2855 to your computer and use it in GitHub Desktop.
simple parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pprint | |
from collections import namedtuple | |
# fields names mapping | |
fields = { | |
"Название": "name", | |
"Сорт": "sort", | |
"Цена": "price", | |
"Картинка": "image", | |
} | |
store = {} # accumulate results here | |
product = {} | |
with open("store.txt") as f: | |
for line in f: | |
line = line.strip() | |
# detect group name | |
if line.startswith("#"): | |
current_group = line[1:].strip() | |
store[current_group] = [] | |
continue | |
# skip empty lines | |
if not line: | |
continue | |
# build product | |
attribue, value = map(str.strip, line.split(":")) | |
try: | |
fieldname = fields[attribue] | |
except LookupError: | |
continue | |
else: | |
product[fieldname] = value | |
if len(product) == 4: # TODO: fix magic constant | |
store[current_group].append(product) | |
product = {} | |
pprint.pprint(store) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment