Skip to content

Instantly share code, notes, and snippets.

@nobbynobbs
Last active October 22, 2019 15:17
Show Gist options
  • Save nobbynobbs/dbffb4cf5f78acfc07e950a964ae2855 to your computer and use it in GitHub Desktop.
Save nobbynobbs/dbffb4cf5f78acfc07e950a964ae2855 to your computer and use it in GitHub Desktop.
simple parser
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