开发者

Parsing Multiple Fields to Single Color Vector in Python

Is there a good pattern in Python to use for parsing multiple lines of an input file into a single value? For example, I've got an input file that looks something like:

BackgroundColor_R=0.0
Back开发者_如何转开发groundColor_G=0.0
BackgroundColor_B=0.0
BackgroundColor_A=0.0
DensityCorrection_Color_R=1.0
DensityCorrection_Color_G=1.0
DensityCorrection_Color_B=1.0

The idea is to get BackgroundColor into a single color vector object as well as DensityCorrection but they are of different sizes and I've like to avoid special logic for each parameter. Any ideas?


Your data has two natural representations, one based on the structure of the config file and one based on the usage within the program. In the spirit of PEP 20 (the Zen of Python) the conversion from one form to another should be explicit.

BackgroundColor = (float(config['BackgroundColor_R']),
                   float(config['BackgroundColor_G']),
                   float(config['BackgroundColor_B']),
                   float(config['BackgroundColor_A']))


You can parse such file with ini file parser. http://docs.python.org/library/configparser.html.

But data structures is up to you. It depends on your needs.


Something like this should work (but using configparser would be better for the first bit):

data = {}

for l in open('input').readlines():
    key, value = l.split("=")
    vector_name = key.split("_")[0]
    vector = data.get(vector_name,[])
    vector.append(value)
    data[vector_name] = vector

print data
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜