简体   繁体   中英

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. 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM