3 """Hack parser for standardizing my Mom's cookbook text.
6 from .cookbook import (
7 Cookbook, Recipe, IngredientBlock, Ingredient, Amount, Directions)
10 class MomParser (object):
11 def parse(self, filename):
13 consecutive_blanks = 100
15 for line in file(filename, 'r'):
16 line = line.strip().decode('utf-8')
18 if recipe_lines != None and consecutive_blanks == 0:
19 recipe_lines.append('')
20 consecutive_blanks += 1
22 if consecutive_blanks >= 2:
23 if recipe_lines != None:
24 c.append(self._parse_recipe(recipe_lines))
27 recipe_lines.append(line)
28 consecutive_blanks = 0
31 def _parse_recipe(self, lines):
33 yield_,author,source,url,lines = self._parse_yield_line(lines)
34 ingredient_blocks,lines = self._parse_ingredient_blocks(lines)
35 directions,lines = self._parse_directions(lines)
36 assert len(lines) == 0, lines
39 ingredient_blocks=ingredient_blocks,
40 directions=directions,
46 def _parse_yield_line(self, lines):
47 while len(lines) > 0 and lines[0] == '':
49 fields = ['yield', 'from', 'source', 'url']
50 yield_ = author = source = url = None
53 if field in lines[0].lower():
56 if matching_line == True:
57 bits = lines.pop(0).split('\t')
60 if bit.lower().startswith(field+':'):
61 value = bit[len(field+':'):].strip()
63 yield_ = value.replace('Serving', 'serving')
66 elif field == 'source':
71 return (yield_, author, source, url, lines)
73 def _parse_ingredient_blocks(self, lines):
74 ingredient_blocks = []
77 while len(lines) > 0 and lines[0] == '': # scroll past blanks
80 or not (first_block == True
81 or lines[0].endswith(':'))):
83 if lines[0].endswith(':'):
85 name = line[:-1].strip()
88 block = IngredientBlock(name)
89 while len(lines) > 0 and lines[0] != '':
90 block.append(self._parse_ingredient_line(lines.pop(0)))
91 ingredient_blocks.append(block)
93 return (ingredient_blocks, lines)
95 def _parse_ingredient_line(self, line):
96 if line.lower().startswith('1 red'):
97 line = '1 # red'+line[len('1 red'):]
99 value,units,name = line.split(' ', 2)
105 elif units == 'Large':
107 elif units == 'Cloves':
109 return Ingredient(name, Amount(value, units))
111 def _parse_directions(self, lines):
112 directions = Directions()
116 if len(paragraph) > 0:
117 directions.append('\n'.join(paragraph))
120 paragraph.append(line)
121 return (directions, [])