Calling a function with unknown number of parameters Python
Asked Answered
C

1

6

I am trying to read in a Fuzzy plain text rule and pass the parameters to a SciKit-Fuzzy function call to create fuzzy rules. For example, if I read in this text rule:

IF service IS poor OR food IS rancid THEN tip IS cheap

Then the function call will be:

ctrl.Rule(service ['poor'] | food ['rancid '], tip ['cheap'])

If text rule is:

IF service IS good THEN tip IS average; 

Then the function call will be:

ctrl.Rule(service ['good '] , tip ['average'])

Since each rule can have unlimited number of input variables, e.g. the user can also say:

IF service IS good AND food IS good AND mood IS happy THEN tip IS high

which contains 3 inputs variables service['good'],food['good'],and mood['happy'], and 1 output variable tip['high']. I can't think of a way to automatically read in the text rule and convert it to a function call, do you have any idea or suggestion to achieve this goal? Any help will be appreciated. Thanks.

Creodont answered 16/8, 2020 at 20:44 Comment(1)
Does this answer your question? Mini-languages in PythonAleenaleetha
P
0

You could try something like this:

string_input = "IF service IS poor OR food IS rancid THEN tip IS cheap"
string_input = string_input.replace(" THEN ", '"], ').replace(' IS ', '["').strip("IF ").replace(" OR ", '"] | ') +'"]'
eval('ctrl.Rule({})'.format(string_input))

But be warned you need to be very very careful with eval. It is a security risk because user can execute code this way!!! Before using this you might to do research on how to prevent this security issue.

Pulmonary answered 16/8, 2020 at 23:38 Comment(2)
This eval() function can solve my problem perfectly. ThanksCreodont
Glad I could help, but as mentioned be aware of potential safety issues if you are considering that user will write that input! Happy Coding!Pulmonary

© 2022 - 2024 — McMap. All rights reserved.