My brain is freezing up again. I have a string that looks something like this
1 apple--1 pear--1 peach--2 onion--2 carrot--3 <bee mince--3 <por chops--4 <oth salad:--potato--4 <oth bread:--garlic
Then I have a few dictionaries:
dic1 = {'1': 'fruit', '2': 'vegetable', '3': 'meat', '4': 'other'}
dic2 = {'bee': 'beef, 'por': 'pork'}
What I'm trying to do is transform this into XML.. sortof.
The output needs to look like this:
<fruit>apple</fruit> <fruit>pear</fruit> <fruit>peach</fruit> <vegetable>onion</vegetable> <vegetable>carrot</vegetable> <meat>beef<type>mince</type></meat> <meat>pork<type>chops</type></meat> <other>(salad)<type>potato</type></other> <other>(bread)<type>garlic</type></other>
fruit, vegetable and meat are easy but I don't know what to do with other. Initially I thought I'd just use split() and then itterate over it using keys() something like this:
items = line.split('--')
for item in items:
if item[0] in dic1.keys:
print '<%s>%s</%s>' % (dic[item0]], item[1:], dic[item0]])
And this works for fruit, vegetables and I can even get meat to behave by adding to that but I don't how I can make other behave. I've even tried writing a recursive function and it almost works but I'm not sure I'm on the right track:
def other(line):
line = line.split('--', 1)
if line[0][0] in dic1.keys():
print '%s\n' % line[0]
elif line[0][0] == '4':
if line[0].endswith(':'):
value = line[1].split('--', 1)
print '%s, %s\n' % (line[0][:-1], value[0])
else:
print '%s\n' % line[0]
if line[1]:
other(line[1])
This almost gets me what I want but I end up with
salad, potato potato bread, garlic garlic
Any help welcome. Thanks