如何在配置解析器从ini文件中获取“单词列表”后将其转换为变量

2024-09-30 16:19:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,它使用配置解析器和一个ini文件获取一个列表 使用此选项是因为最终用户将把自己的列表放入排序脚本中

config.ini文件的一部分示例

[ConfigFile]
#L1 Category to Keep
l1cat=('Audio Terminal', 'Communications/Telephone', 'Microphones', 'Speakers', 'Tour Sound')

我的脚本中有这个来获取ini文件

import configparser
from configparser import ConfigParser
config = ConfigParser()
config.read("SortingConfig.ini")
config.sections()


def variables(section):
    dict1 = {}
    options = config.options(section)
    for option in options:
        try:
            dict1[option] = config.get(section, option)
            if dict1[option] == -1:
                DebugPrint("skip: %s" % option)
        except:
            print("exception on %s!" % option)
            dict1[option] = None
    return dict1

我遇到的问题是。。。。 正在扭转局面

l1cat=('Audio Terminal', 'Communications/Telephone', 'Microphones', 'Speakers', 'Tour Sound')

转换为可用的变量值

在我的剧本中,我有这个

xls_book = xlrd.open_workbook(infilepath, formatting_info = True, encoding_override = "cp1252", logfile = open(os.devnull, 'w'))
sheetname = xls_book.sheet_by_index(0).name

df = pd.read_excel(xls_book, engine = 'xlrd',parse_dates = ['Date'])
df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%y %H:%M:%S').dt.strftime('%m/%d/%y %H:%M')

## L1 Category keep if isin list
df = df.loc[df['L1 Category'].isin(l1cat)]

我得到的错误是 TypeError:仅允许将类似列表的对象传递给isin(),您传递了[str]

在最终用户需要对其进行动态更改之前,我可以将l1cat=('stuff'、'more stuff'、'ever more stuff')添加为一个正则变量,它工作得非常好

我之所以使用配置解析器,是因为当我编译成EXE时,我需要一些可以通过配置文件随时更改变量的东西

实际上,我需要它像直接在脚本中输入l1cat = ('stuff','more stuff','even more stuff')一样工作


修复的文件看起来像这样,仍然使用与上面相同的ini示例

import configparser
from configparser import ConfigParser
from ast import literal_eval
config = ConfigParser()
config.read("SortingConfig.ini")
config.sections()


def variables(section):
    dict1 = {}
    options = config.options(section)
    for option in options:
        try:
            dict1[option] = config.get(section, option)
            if dict1[option] == -1:
                DebugPrint("skip: %s" % option)
        except:
            print("exception on %s!" % option)
            dict1[option] = None
    return dict1

#The Variable gets Defined
l1catV = literal_eval(config['ConfigFile']['l1cat'])

###Further down in my script as I need to use the variable
xls_book = xlrd.open_workbook(infilepath, formatting_info = True, encoding_override = "cp1252", logfile = open(os.devnull, 'w'))
sheetname = xls_book.sheet_by_index(0).name

df = pd.read_excel(xls_book, engine = 'xlrd',parse_dates = ['Date'])
df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%y %H:%M:%S').dt.strftime('%m/%d/%y %H:%M')

## L1 Category keep if isin list

##Variable gets used
df = df.loc[df['L1 Category'].isin(l1catV)]


Tags: importconfigl1dfdatesectionxlsini
2条回答

我似乎有它的工作。。。除了部分解析返回了错误的变量,我不确定我遗漏了什么

在my config.ini中

[section]
#Color 1
color01 = ('00FCC84E')
cat1 = ('Speakers','Atlas Mic Stands')

#Color 2
color02 = ('00F4426E')
cat2 = ('Audio Mixers/Console')


当我使用

color01V = literal_eval(config['ConfigFile']['color01'])
color02V = literal_eval(config['ConfigFile']['color02'])


cat01V = literal_eval(config['ConfigFile']['cat1'])
cat02V = literal_eval(config['ConfigFile']['cat2'])


print(cat01V)

print(cat02V)

一个带()返回,另一个不带。。。。 我需要做什么才能让这两个都返回()

('Speakers', 'Atlas Mic Stands')
Audio Mixers/Console

您可以使用ast.literal_evaldoc)来解析值:

txt = '''
[ConfigFile]
#L1 Category to Keep
l1cat=('Audio Terminal', 'Communications/Telephone', 'Microphones', 'Speakers', 'Tour Sound')
'''

import configparser
from configparser import ConfigParser
from ast import literal_eval

config = ConfigParser()
#####config.read_string(txt)###### - This portion was incorrect



my_tuple = literal_eval(config['ConfigFile']['l1cat'])

for val in my_tuple:
    print(val)

印刷品:

Audio Terminal
Communications/Telephone
Microphones
Speakers
Tour Sound

相关问题 更多 >