【问题】
I have a text file with content like, with 792 lines:
der 17788648
und 14355959
die 10939606
Die 10480597
Now I want to compare if "Die" and "die" are equal in lowercase. So if two Strings in lowerCase are equal, copy the word into a new text file in lowerCase and sum the values.
Expected output:
der 17788648
und 14355959
die 21420203
I have that so far:
try {
BufferedReader bk = null;
BufferedWriter bw = null;
bk = new BufferedReader(new FileReader("outagain.txt"));
bw = new BufferedWriter(new FileWriter("outagain5.txt"));
List<String> list = new ArrayList<>();
String s = "";
while (s != null) {
s = bk.readLine();
list.add(s);
}
for (int k = 0; k < 793; k++) {
String u = bk.readLine();
if (list.contains(u.toLowerCase())) {
//sum values?
} else {
bw.write(u + "\n");
}
}
System.out.println(list.size());
} catch (Exception e) {
System.out.println("Exception caught : " + e);
}
【回答】
这是简单的分组汇总,JAVA没有通行的结构化计算类库,硬编码很繁琐。可以用SPL实现,只要一句。
| A | |
| 1 | =file("d:\\data.txt").import(;," ").groups(lower(#1);sum(#2)) |
| 2 | =file("d:\\result.txt").export(A1; " ") |
A1:按第1个字段的小写分组,按第2个字段汇总。
A2:如果想把结果写到文件,可以再加此句。
这段代码可以方便地集成进Java,参考Java 如何调用 SPL 脚本。
本文介绍了一种使用Java处理文本文件的方法,并通过SPL简化了数据处理流程。具体需求为比较文本文件中字符串的大小写并进行汇总,最终将结果输出到新的文本文件中。SPL提供了一行代码解决方案,极大提高了处理效率。
686

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



