【问题】
I have a text file like this:
key1 value1 A key1 value2 B key1 value3 A key2 value1 A key2 value2 B
I am trying to open it as a dictionary and print the list of keys and values separated by commas so it looks like this in the end:
key1 value1,value2,value A,B,A key2 value1,value2,value A,B
I am trying the following code:
f = open('file.txt', 'r') answer = {} for line in f: list = ",".join(map(str,f)) print list But it's not working
【回答】
分组后合并组内成员是简单的 SQL 式计算,用 Python 实现的代码较为复杂,这类运算更适合集算器,SPL 代码很简单:
A | |
1 | =file("file.txt").import() |
2 | =A1.group(_1;~.(_2).concat@c(),~.(_3).concat@c()) |
A2:按 _1 分组,并且将分组后的 _2 和 _3 字段用逗号分隔合并
集算器提供 JDBC 接口,可以像数据库一样嵌入到应用程序中,用起来很简单,可参考Java 如何调用 SPL 脚本。