简体   繁体   English

如何从字符串中获取项目并将其用作值

[英]How to take the item from string and use it as a value

I have a string and I need to use this string to fit a model.我有一个字符串,我需要使用这个字符串来适应 model。 However when I try try to do this, of course it raises an error which can be seen below.但是,当我尝试这样做时,当然会引发一个错误,如下所示。 How can I use this string to fit the model?我怎样才能使用这个字符串来适应 model?

import re
best_model_final = 'LinearRegression(fit_intercept=True,normalize=True)'
best_model_name = re.sub("[\(\[].*?[\)\]]", "", best_model_final )
best_model_name.fit(X.iloc[:-1], y.iloc[:-1])

AttributeError: 'str' object has no attribute 'fit'

You need to evaluate the string into a Python object, ie do您需要将字符串评估为 Python object,即执行

best_model_final = 'LinearRegression(fit_intercept=True,normalize=True)'
best_model_name = re.sub("[\(\[].*?[\)\]]", "", best_model_final )
best_model = eval(best_model_name)
best_model.fit(X.iloc[:-1], y.iloc[:-1]

See documentation of eval() https://docs.python.org/3/library/functions.html#eval请参阅eval() https://docs.python.org/3/library/functions.html#eval的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Python中的字符串中获取日期值? - how to take date value from string in python? 如何遍历导入的 excel 文档中的行并获取字符串值并使用它来命名最终图像输出 - How to loop through rows from an imported excel doc and take the string value and use that to name the final image output 如何从字符串中获取项目的值? - How to get the value of an item from the string? 如何从argparse的输入中获取字符串并将其用作对象 - How to take the string from input of argparse and use it as an object 如何从参数中获取字符串并在if语句中使用它? - How would I take a string from an argument and use it in an if statement? 如何从 Python Pandas 中的 DataFrame 中的列中获取字符串值? - How to take part of string value from column in DataFrame in Python Pandas? 如何从一个函数中获取一个值并在另一个函数中使用它? - How do I take a value from one function and use it in another? 如何从键值中获取并从该值中获取另一个值 - How to take from key value and take from this value another value 如何取一个字符串并将其用作标识符来调用函数? - How to take a string and use it as an identifier to call a function? 如何使用str.replace从旋转框获取值,然后在文本文件中替换该值的实例? - How can I use a str.replace to take a value from a spinbox, and then replace an instance of that value in a text file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM