我有一个很大的 txt 文件(2GB)。我使用以下代码片段逐个字符读取整个 txt 文件,以找出整个 txt 文件中每个字符的频率。
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file),
Charset.forName("UTF-8")));
int c;
while ((c = reader.read()) != -1) {
char ch = (char) c;
// rest of the code
}
现在我需要生成一个包含连续字符频率的矩阵。 例如,字符“b”在字符“a”之后出现了多少次(连续的、直接的字符),反之亦然。
假设,我有一个输入字符串(来自文件):cad bed abed dada
频率矩阵就像 Please click here to see the image
如何做到这一点?将不胜感激任何帮助和建议。 谢谢。
最佳答案
跟踪最后读取的字符。如果lastchar=='' 继续。使用 Map 来存储值。然后您可以循环组合并从 Map 中提取值,或者您可以通过从当前字符对中减去 char 'a' 的 int 值来直接寻址二维数组。
Map<String, Integer> table = new HashMap<>();
String last = "";
for (char c : input.toCharArray()) {
if (last.isEmpty()) {
last = String.format("%c", c);
continue;
}
String thing = last + c;
Integer count = table.getOrDefault(thing, 0);
table.put(thing, count + 1);
last = String.format("%c", c);
}
关于java - 如何从java中的txt文件生成连续字符频率矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56191580/