gpt4 book ai didi

java - 如何比较字符串数组并计算相似单词

转载 作者:行者123 更新时间:2023-12-02 04:09:18 24 4
gpt4 key购买 nike

我一直在尝试获取此代码,但仍然无法。这个代码段是我能做的最接近的。我缺少什么?我正在尝试在没有哈希的情况下执行此代码。

    // Read all the words from the dictionary (text.txt) into an array
BufferedReader br = new BufferedReader(new FileReader("text.txt"));
int bufferLength = 1000000;
char[] buffer = new char[bufferLength];
int charsRead = br.read(buffer, 0, bufferLength);
br.close();
String text = new String(buffer);
text = text.trim();
text = text.toLowerCase();
String[] words = text.split("\n");

System.out.println("Total number of words in text: " + words.length);

//Find unique words:
String[] uniqueText = words;
int[] uniqueTextCount = new int[uniqueText.length];

for (int i = 0; i < words.length; i++) {
for (int j = 0; j < uniqueText.length; j++) {
if (words[i].equals(uniqueText[j])) {
uniqueTextCount[j]++;
} else {
uniqueText[i] = words[i];
}
}
System.out.println(uniqueText[i] + " for " + uniqueTextCount[i]);
}
}

最佳答案

根据您的原始代码,我假设:

  • text.txt 每行包含一个单词。
  • 您想要计算每个单词出现的次数(而不是标题中所写的“相似单词”)。

也许第一件事是 BufferedReader 允许 line-by-line reading :

for (String line; (line = br.nextLine()) != null; ) {
// Process each line, which in this case is a word.
}

逐行处理比读取整个文件更可取,因为您的程序将需要使用更多的内存(与文件的大小一样多),而您可以使用更少的内存。

现在,如果我们考虑一下需求,所需的输出是从不同单词到其计数的映射。这应该出现在上面的 for 循环之前。

// A HashMap would also work, but you have specified that you do not want
// to use hashing.
Map<String, Integer> distinctWordCounts = new TreeMap<>();

当初始化时,在循环中的每次迭代中(即,对于我们遇到的每一行),我们可以执行以下操作:

if (distinctWordCounts.hasKey(line)) {
// We have seen this word. Increment the count we've seen it.
distinctWordCounts.put(line, distinctWordCounts.get(line) + 1);
} else {
// We have never seen this word. Set the count seen to 1.
distinctWordCounts.put(line, 1);
}

上面的代码产生的开销比看起来最优的要多一点,因为 if 情况涉及 3 次遍历,而我们可以只进行一次遍历。但这可能是另一天的故事,除非您有理由关心非渐近速度的改进。

最终,我们可以遍历 distinctWordCounts 来计算单词数

for (Entry<String, Integer> entry : distinctWordCounts.entrySet()) {
System.out.println(entry.getKey() + " occurs " + entry.getValue() + "times.");
}

关于java - 如何比较字符串数组并计算相似单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33947852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com