I am trying to parse the function f = sin(2*pi*x) from a text file. In the main code the function stay inside a for loop and will take the input value for x which is already defined. Now, how can I parse this function to my main code to get floating number outputs for the function? I am new in python. Any kind of help is much appreciated. Thanks.
Asked
Active
Viewed 437 times
0
-
1Could you elaborate please? – Toady Jan 13 '19 at 22:58
-
1Please clarify your question with more details. Your point is prone to being misunderstood. So you have a text file, `myFile.txt`, and it contains the function definition, correct? If so, please fully paste into your question what is in the text file. And tell us what you want to do with it. – FatihAkici Jan 13 '19 at 23:01
-
Thanks for your reply. I have corrected the post. So, in my text file I have the function and want to parse it in my main code so that I can evaluate the function for different values of x. – Md Mahmudul Hasan Jan 13 '19 at 23:23
1 Answers
0
You can use eval
. But before reading further be aware that using eval
can be prone to exploits. If you have no control over the input (i.e. the function) then you'll need to triple check to perform the appropriate sanity checks on the input string.
f = 'sin(2*pi*x)'
for x in [...]:
y = eval(f, {}, {'sin': np.sin, 'pi': np.pi, 'x': x})
If you can define some structure for the input functions, it's better parse the strings directly, using regex for example, and then compute the result. But that depends on what is possible as an input.

a_guest
- 34,165
- 12
- 64
- 118
-
The way you’ve written y, I have to write it down exactly the same way or you are just elaborating that eval will convert the string into that manner(i.e ‘sin’: np.sin, ...)? I am calculating the values for x using linspace so that, I can get different values of the function for different x. – Md Mahmudul Hasan Jan 14 '19 at 02:47
-
You need to provide a dictionary of objects that are (may be) present in the string, so it can resolve names during evaluation. You could also use `eval(f, {}, np.__dict__)` but it's better to narrow it down to the essential attributes and only provide those. Also helps in debugging. – a_guest Jan 14 '19 at 14:45