【发布时间】:2021-04-06 08:02:50
【问题描述】:
我正在为我的期末论文做一个相对较大的项目,因此我使用 .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)
但是,这似乎非常不优雅,嵌套如此之多,而且任务本身似乎如此重要,以至于我无法相信没有“更官方”的解决方案,我根本无法找到。
那么,请有人在这里帮助我,告诉我是否真的没有更好、更直接的方法来实现这一目标!?
【问题讨论】:
标签: python parsing ini configparser