简体   繁体   English

在Python中从文本文件导入方程式

[英]Import equation from text file in Python

I have a complex equation which is generated into a .txt file. 我有一个生成到.txt文件的复杂方程式。 I would like to import this equation (which is all the text in the .txt file) and make a function from it, which can be subsequently fit. 我想导入此等式(这是.txt文件中的所有文本)并从中创建一个函数,随后可以对其进行拟合。

Does anybody know how I might go about this? 有人知道我该怎么做吗? The equation to be fitted is at the the very bottom. 要拟合的方程式位于最底部。 My feeble attempt to import is below... 我尝试导入的能力不足...

myfile1= open("dummyfile.txt", 'r') 
def fcn(J1,J2,T,k,g):
    return myfile1.read()

"dummyfile.txt" contents: “ dummyfile.txt”内容:

B**2*N*(12.0*g**2*sp.exp(2.0*J2/(T*k)) + 60.0*g**2*sp.exp(6.0*J2/(T*k)) + 168.0*g**2*sp.exp(12.0*J2/(T*k)) + 360.0*g**2*sp.exp(20.0*J2/(T*k)) + 30.0*g**2*sp.exp((2.0*J1 + 4.0*J2)/(T*k)) + 168.0*g**2*sp.exp((4.0*J1 + 8.0*J2)/(T*k)) + 360.0*g**2*sp.exp((6.0*J1 + 14.0*J2)/(T*k)) + 180.0*g**2*sp.exp((8.0*J1 + 12.0*J2)/(T*k)) + 660.0*g**2*sp.exp((8.0*J1 + 22.0*J2)/(T*k)) + 660.0*g**2*sp.exp((12.0*J1 + 18.0*J2)/(T*k)) + 1092.0*g**2*sp.exp((16.0*J1 + 26.0*J2)/(T*k)) + 546.0*g**2*sp.exp((18.0*J1 + 24.0*J2)/(T*k)) + 1680.0*g**2*sp.exp((24.0*J1 + 32.0*J2)/(T*k)) + 1224.0*g**2*sp.exp((32.0*J1 + 40.0*J2)/(T*k)))/(3*T*k*(6*sp.exp(2.0*J2/(T*k)) + 10*sp.exp(6.0*J2/(T*k)) + 14*sp.exp(12.0*J2/(T*k)) + 18*sp.exp(20.0*J2/(T*k)) + 5*sp.exp((2.0*J1 + 4.0*J2)/(T*k)) + 14*sp.exp((4.0*J1 + 8.0*J2)/(T*k)) + 18*sp.exp((6.0*J1 + 14.0*J2)/(T*k)) + 9*sp.exp((8.0*J1 + 12.0*J2)/(T*k)) + 22*sp.exp((8.0*J1 + 22.0*J2)/(T*k)) + 22*sp.exp((12.0*J1 + 18.0*J2)/(T*k)) + 26*sp.exp((16.0*J1 + 26.0*J2)/(T*k)) + 13*sp.exp((18.0*J1 + 24.0*J2)/(T*k)) + 30*sp.exp((24.0*J1 + 32.0*J2)/(T*k)) + 17*sp.exp((32.0*J1 + 40.0*J2)/(T*k)) + 1))

You can do that with exec() . 您可以使用exec()做到这一点。

Code: 码:

def build_function(filename):
    with open(filename, 'rU') as f:
        eqn = f.read().strip()
        exec("def fcn(J1, J2, T, k, g):\n return ({})".format(eqn))
        return locals()['fcn']

Test Code: 测试代码:

fcn = build_function('file1')
print(fcn(1, 2, 3, 4, 5))

File1: 文件1:

J2 + T*k

Results: 结果:

14

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

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