Skip to content

Instantly share code, notes, and snippets.

@simos
Created November 12, 2013 10:55
Show Gist options
  • Save simos/7429085 to your computer and use it in GitHub Desktop.
Save simos/7429085 to your computer and use it in GitHub Desktop.
Parses a parameterlist.htm file and creates a dictionary(hash table) with the data.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# We open the file and create the handle 'f' to access the content.
f = open("parameterlist.htm", 'r')
# The variable 'lines' now has all the lines of the file. 'lines' is an array.
lines = f.readlines()
# We initialise a hash table (dictionary) that we will put the parsed parameters in.
# At the end, we can access the variables as in
# parameters['monthtodateavgtemp']
parameters = {}
# We go through every line in the 'lines' array and extract the parameters.
for l in lines:
# Every lines ends with <br>. We remove that '<br>'.
# l[:-5] means that we ignore the last 5 characters of the line.
# '<br>^M' is five characters, ^M is a single character for newline.
proper_line = l[:-5]
# If the line is empty, go up and try the next line.
if proper_line.__len__() == 0:
continue
# If the line starts with '#' (comment), we ignore as well.
# The very first line of the file starts with a special character
# so we ignore as well.
if proper_line[0] == '#' or proper_line[0] == '\xef':
continue
# We extract the variable name and value, by spliting the string
# 'items' is an array, items[0] is variable name, items[1] is value.
items = proper_line.split('=', 2)
# Uncomment this if you want to see each line being printed.
#print items
# Some lines, like 'genExtraHumidity20', have no value, so the
# spliting above only produces the name (items[0]) and no items[1]
# With the following code we handle both cases.
try:
# The most common case that works all the time
# If items[1] is not defined, Python will run instead the
# version that is located under the 'except IndexError' line.
parameters[items[0]] = items[1]
except IndexError:
# In the case there is no value, we add an empty value.
parameters[items[0]] = ''
for variable, value in parameters.items():
print "The variable:", variable, "and the value is:", value
print
print "For example, the MonthToDataAVGTemp is", parameters['monthtodateavgtemp']
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment