java - Java中的重复词频问题
问题描述
[我是 Java 和 Stackoverflow 的新手。我的最后一个问题已结束。这次我添加了完整的代码。谢谢] 我有一个 4GB 的大 txt 文件(vocab.txt)。它包含简单的孟加拉语(unicode)单词。每个单词都以其频率换行(之间的等号)。如,
আমার=5
তুমি=3
সে=4
আমার=3 //duplicate of 1st word of with different frequency
করিম=8
সে=7 //duplicate of 3rd word of with different frequency
如您所见,它多次使用不同频率的相同单词。如何只保留一个单词(而不是多个重复)以及重复单词的所有频率的总和。例如,上面的文件就像(output.txt),
আমার=8 //5+3
তুমি=3
সে=11 //4+7
করিম=8
我已经使用 HashMap 来解决这个问题。但我想我在某个地方犯了一些错误。它运行并将确切的数据显示到输出文件而不更改任何内容。
package data_correction;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.util.*;
import java.awt.Toolkit;
public class Main {
public static void main(String args[]) throws Exception {
FileInputStream inputStream = null;
Scanner sc = null;
String path="C:\\DATA\\vocab.txt";
FileOutputStream fos = new FileOutputStream("C:\\DATA\\output.txt",true);
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(fos,"UTF-8"));
try {
System.out.println("Started!!");
inputStream = new FileInputStream(path);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
line = line.trim();
String [] arr = line.split("=");
Map<String, Integer> map = new HashMap<>();
if (!map.containsKey(arr[0])){
map.put(arr[0],Integer.parseInt(arr[1]));
}
else{
map.put(arr[0], map.get(arr[0]) + Integer.parseInt(arr[1]));
}
for(Map.Entry<String, Integer> each : map.entrySet()){
bufferedWriter.write(each.getKey()+"="+each.getValue()+"\n");
}
}
bufferedWriter.close();
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
System.out.print("FINISH");
Toolkit.getDefaultToolkit().beep();
}
}
谢谢你的时间。
解决方案
这应该用一些更多的 eJava 魔法来做你想做的事情:
public static void main(String[] args) throws Exception {
String separator = "=";
Map<String, Integer> map = new HashMap<>();
try (Stream<String> vocabs = Files.lines(new File("test.txt").toPath(), StandardCharsets.UTF_8)) {
vocabs.forEach(
vocab -> {
String[] pair = vocab.split(separator);
int value = Integer.valueOf(pair[1]);
String key = pair[0];
if (map.containsKey(key)) {
map.put(key, map.get(key) + value);
} else {
map.put(key, value);
}
}
);
}
System.out.println(map);
}
获取正确的test.txt
文件路径。注意地图保存在内存中,所以这可能不是最好的方法。如有必要,用例如数据库支持的方法替换地图。
推荐阅读
- javascript - 如何在javascript中的函数名称中包含变量(字符串)?
- r - R-我如何使用地图函数来计算小标题中许多分组列的平均值
- python - 对给定 id 的 pandas 列中的最新值进行分组
- optimization - 如何不通过 GraphQL 暴露重复的(规范化?)节点?
- flask - Flask SQLAlchemy对具有给定值的多个列的唯一约束
- shopify - Shopify 触发器
- regex - 从用户代理中提取应用程序名称
- c# - EF Core 3.0.0 - 两个相同类型的一对一关系
- javascript - 按对象属性数组过滤数组
- python - 在视频类型的源设备中找不到名称为 [集成摄像头] 的视频设备