Skip to content

Instantly share code, notes, and snippets.

@robcowie
Created June 20, 2011 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robcowie/1035938 to your computer and use it in GitHub Desktop.
Save robcowie/1035938 to your computer and use it in GitHub Desktop.
Stackoverflow question 6413439 answer
def extract_day_month(line, context):
"""Handle user defined variables, day and month"""
parts = line.split()
context['user_defined_month'] = [1]
context['user_defined_day'] = [4]
def extract_re(pattern):
"""Return a callable that adds matched group values to context dict
"""
def _extractor(line, context):
patt = re.compile(pattern)
context.update( patt.findall() )
return _extractor
extractors = {
'month:' : extract_day_month,
'solar zenith angle' : extract_re(r'[\s+](?P<user_defined_solar_zenith>[0-9\.]+) deg')
}
def parse(infile):
## Ignore 'blank' lines
infile = (line for line in infile if
line.replace('*', '').replace(' ', '').replace('-', ''))
context = {}
for line in infile:
for label, extractor in extractors.iteritems():
if label in line:
extractor(line, context)
break
print(context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment