Created
June 20, 2011 16:27
-
-
Save robcowie/1035938 to your computer and use it in GitHub Desktop.
Stackoverflow question 6413439 answer
This file contains 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
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