2016-02-17 83 views
2

我正在嘗試創建一個開放式報表結構,其中人們可以用基本上字符串替換的公式定義報表。python模塊/框架的數學公式?

喜歡的東西:

'my_report': { 
    'my_stat': '{units}/({units}+{other_units})*100' 
} 

,然後將這些將包含所有在報告中允許值的dict解析。

有一百個左右的可能的密鑰和框架,需要允許任何有效的數學公式,所以你會碰到這樣的:

my_stat = formula.parse(d) 

哪裏d是實際值的字典。

有沒有一個框架或模塊已經支持這個?

+0

也可能會考慮模板庫中像Jinja2的。 –

回答

3

可以使用的formateval結合自己的發展呢:

class Formula(): 
    def __init__(self, formula): 
     self.formula = formula 

    def parse(self, d): 
     return eval(self.formula.format(**d)) 

formula = Formula('{units}/({units}+{other_units})*100') 
d = {'units': 100.0, 'other_units': 50.0} 

my_stat = formula.parse(d) 

print my_stat 

回報

66.6666666667