使用 configparser 从配置文件中解析数字和列表
Parse numbers and lists from config files with configparser
我正在为我的期末论文做一个相对较大的项目,因此我使用 .ini 文件来存储和检索设置。但是,我无法找到一个优雅的解决方案来解决如何将 Configparser returns 的字符串(嗯,实际上是字典中的字符串)转换为数字(整数和浮点数)and/or 列表。
谷歌搜索这个问题,我遇到了 this SO thread,它只解决了我问题的 'list' 部分,但使用了评价最高的解决方案(在 .ini 文件中定义列表,如下所示:list=item1 ,item2) 对我没有任何作用,因为 'list' 在解析后仍然显示为字符串。另外,我不想更改格式。
所以我决定自己尝试并提出这个解决方案:
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)
然而,这看起来非常不雅并且嵌套如此严重,而且任务本身看起来如此重要,以至于我无法相信没有我根本找不到的“更官方”的解决方案。
所以,请有人帮助我,告诉我是否真的没有更好、更直接的方法来实现这一目标!?
我能做的最好的就是这个(虽然它有点老套而且可能也很危险):
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]
这对于 ints
、floats
以及您的逗号分隔值都可以正常工作(它将把它作为一个元组进行评估,我想这应该没问题,尽管我为此添加了一个条件无论如何)。
我正在为我的期末论文做一个相对较大的项目,因此我使用 .ini 文件来存储和检索设置。但是,我无法找到一个优雅的解决方案来解决如何将 Configparser returns 的字符串(嗯,实际上是字典中的字符串)转换为数字(整数和浮点数)and/or 列表。
谷歌搜索这个问题,我遇到了 this SO thread,它只解决了我问题的 'list' 部分,但使用了评价最高的解决方案(在 .ini 文件中定义列表,如下所示:list=item1 ,item2) 对我没有任何作用,因为 'list' 在解析后仍然显示为字符串。另外,我不想更改格式。
所以我决定自己尝试并提出这个解决方案:
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)
然而,这看起来非常不雅并且嵌套如此严重,而且任务本身看起来如此重要,以至于我无法相信没有我根本找不到的“更官方”的解决方案。
所以,请有人帮助我,告诉我是否真的没有更好、更直接的方法来实现这一目标!?
我能做的最好的就是这个(虽然它有点老套而且可能也很危险):
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]
这对于 ints
、floats
以及您的逗号分隔值都可以正常工作(它将把它作为一个元组进行评估,我想这应该没问题,尽管我为此添加了一个条件无论如何)。