I am trying to do some translation of text files. I have a translation .csv file and a file I need to translate (tab delimited). The translation is creating a file with an extra column of the translation.
I'd like to hear any suggestions on this.
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TextFileManipulationExample {
public static void main(String[] args) {
new TextFileManipulationExample().translate();
}
private void translate() {
List<String> translationFileContent = readFile("dictionary.csv");
Stream<List<String>> translationLines = translationFileContent.stream().map(
line -> Splitter.on(",").splitToList(line));
Map<List<String>, String> translationMap = translationLines.collect(Collectors.toMap(l -> Lists.newArrayList(l.subList(0, 2)), l -> l.get(2)));
List<String> toTranslateLines = readFile("file_to_translate.txt");
Stream<List<String>> listWithTranslation = toTranslateLines.stream().map(line -> {
List<String> list = Lists.newArrayList(Splitter.on("\t").splitToList(line));
if (translationMap.containsKey(list)) {
list.add(translationMap.get(list));
}
return list;
});
String contentToWrite = listWithTranslation.map(lineList -> Joiner.on(",").join(lineList)).collect(
Collectors.toList()).stream().reduce((t, u) -> t + "\n" + u).get();
writeFile(contentToWrite, "translated.csv");
}
private void writeFile(String contentToWrite, String fileName) {
try {
Files.write(contentToWrite, new File(fileName), Charset.defaultCharset());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private List<String> readFile(String fileName) {
try {
return Files.readLines(new File(fileName), Charset.defaultCharset());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Map<List<String>, String> translationMap
: Does it mean that translating "hi" and "hey" to "g'day" will contain the following entry?["hi", "hey"] => "g'day"
\$\endgroup\$