【原帖】
I have a CSV file with formulae, like this:
1;;2.74;0 =A1+C1;=A2;=C1
What’s the best way to convert formulae into numbers, as follows
1;;2.74;0 3.74;3.74;2.74
?
The only way I know is to read it with csv.reader as a list of lists and then loop through each element. But it seems there must be a simpler way.
P. S. I have a hint to use eval
【回答】
这个问题的难点在于,不仅要动态解析字符串表达式,而且表达式里还有类似Excel格名的变量。如果能把这个csv贴进Excel,马上就能计算完,用VBA也可以做到,但很多情况下只有这个csv,没有Excel,就只能求助于其他脚本语言。
格名不是Excel的专利, esProc SPL也支持格名变量,且支持动态表达式运算,特别适合解决此类问题。具体到这个问题,可以这样写:
| A | B | C | D | E | |
| 1 | /预留前2行 | ||||
| 2 | |||||
| 3 | =file("D:\data.csv").import(;,";") | ||||
| 4 | =A3(1).array().(eval(char(64+#) / "1=" / if(~==null,"null",~))) | /处理第1行 | |||
| 5 | =A3(2).array().(eval(char(64+#) / "2" / if(~==null,"=null",~))) | /第2行 | |||
| 6 | =create(A,B,C,D).record([A1:D2]) | /计算结果 | |||
| 7 | =file("D:\result.csv").export(A6;";") | ||||
SPL很擅长处理xls/csv上的运算,这里:» Might Script on File - RAQSOFT 有更多资源。
本文探讨了如何将包含公式(如=A1+C1)的CSV文件中的表达式转换为数值,提出了一种利用Python的eval函数结合esProcSPL进行动态计算的方法,以简化从列表列表中逐行处理的繁琐过程。
686

被折叠的 条评论
为什么被折叠?



