【问题标题】:get a string without "" [closed]得到一个没有“”的字符串[关闭]
【发布时间】:2022-01-24 19:11:08
【问题描述】:

我正在尝试自动化 PyCaret 库中的设置过程。 目标是创建一个“实验”列表,脚本应该对元素列表进行迭代。

在设置中可以选择以下预处理步骤: 特征选择=真, remove_outliers = True 等。

我希望将所有此类预处理步骤存储在一个列表中,然后运行一个循环以找到模型的最佳设置(最佳性能)。

例如:

a = "feature_selection = True"
b = "remove_outliers = True"

等等。

但是当我在设置中调用变量“a”时,我得到:

  File "<ipython-input-31-0d8c8dcb30cf>", line 7
    a
    ^
SyntaxError: positional argument follows keyword argument

因为变量“a”不能很好地完成这项工作。

reg = setup(data = df, silent = True, test_data = dff, target = 'Thickness',
            verbose = False,
            numeric_features = ['Airbubbles','PreHeat','PlugTemp','AirPres','VacPress','MoldTemp'],
            a
           )

如果我将变量称为“a”,则会显示以下内容: 'feature_selection = True'

因此,我需要以其他方式存储列表的字符串,以便显示为:feature_selection = True(不带'')并被 PyCaret 的设置接受。

【问题讨论】:

    标签: python pandas string


    【解决方案1】:

    假设你有一个这样的字符串:

    >>> a = "feature_selection = True"
    >>> a
    "feature_selection = True"
    

    为了将其作为关键字参数 (kwarg) 传递给函数(例如,my_func(feature_selection=True)),您需要将其转换为字典:

    >>> import re
    >>> d = dict([re.split('\s*=\s*', a)])
    {'feature_selection': 'True'}
    

    您可能希望将键转换为实际的文字值,例如'True'(字符串)-> True(布尔):

    import ast
    
    for k, v in d.items():
        d[k] = ast.literal_eval(v)
    

    然后,您可以将它传递给这样的函数:

    my_func(**d)
    

    例如

    reg = setup(data = df, silent = True, test_data = dff, target = 'Thickness',
                verbose = False,
                numeric_features = ['Airbubbles','PreHeat','PlugTemp','AirPres','VacPress','MoldTemp'],
                **d,
               )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 2015-01-27
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多