使用 configparser 从配置文件中解析数字和列表

时间:2020-12-29 17:45:44

标签: python parsing ini configparser

我正在为我的最终论文做一个相对较大的项目,因此我使用 .ini 文件来存储和检索设置。但是,我无法找到一个优雅的解决方案,用于将 Configparser 返回的字符串(实际上是字典中的字符串)转换为数字(整数和浮点数)和/或列表。

谷歌搜索这个问题,我遇到了 this SO thread ,它只解决了我的问题的“列表”部分,但使用最受好评的解决方案(在 .ini 文件中定义列表,如:list=item1,item2)没有对我没有任何作用,因为解析后“列表”仍然显示为字符串。另外,我不想改变格式。

所以我决定自己尝试一下,并想出了这个解决方案:

import configparser 

# create a new instance of a 'ConfigParser' class
config = configparser.ConfigParser()
# create mock-content for the config file
config["Test"] = {
"test_string":"string",
"test_int":"2",
"test_float":"3.0",
"test_list":"item1, item2"
}
# get the relevant settings
settings = config["Test"]
# pack the relevant settings into a dictionary
settings = dict(settings)
# iterate through all the key-value pairs and convert them, if possible
for key, value in settings.items():
    # try to convert to int
    try:
        settings[key] = int(value)
    # if the value can't be converted to int, it might be a float or a list
    except ValueError:
        # try converting it to a float
        try:
            settings[key] = float(value)
        # if the value can't be converted to float, try converting to list
        except ValueError:
            if "," in value:
                cont = value.split(",")
                settings[key] = [item.strip() for item in cont]
            else:
                settings[key] = value
print(type(settings["test_string"]))
print(settings)

然而,这看起来非常不优雅,嵌套如此严重,而且任务本身似乎如此重要,以至于我无法相信没有“更官方”的解决方案,我根本无法找到。

所以,请有人帮我一下,告诉我是否真的没有更好、更直接的方法来实现这一目标!?

1 个答案:

答案 0 :(得分:2)

我能做的最好的就是这个(虽然它有点老套而且可能也很危险):

for key, value in settings.items():
    try: # will handle both ints and floats, even tuples with ints/floats
        settings[key] = eval(value)
    except NameError: # this means it's a string or a tuple with strings
        get_val = list(map(str.strip, value.split(",")))
        settings[key] = get_val if get_val[1:] else get_val[0]

这将适用于 intsfloats 以及您的逗号分隔值(它会将其评估为元组,我想这应该没问题,尽管我为此添加了条件) .