【问题标题】:How to compare String Array and count similar words如何比较字符串数组并计算相似词
【发布时间】:2017-05-19 07:10:14
【问题描述】:

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

    // 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]);
    }
}

【问题讨论】:

  • 对不起格式!我是 stackoverflow 和编程的新手
  • 请在此处复制并粘贴代码,而不是发布图像。让这里的用户更容易自己尝试代码。
  • String[] uniqueText = words; int[] uniqueTextCount = new int[uniqueText.length]; for (int i = 0; i
  • 用它而不是图像来编辑您的原始帖子。
  • 我尝试过,但一直收到错误消息

标签: java arrays


【解决方案1】:

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

  • 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-loop 之前。

// 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 的情况涉及三个遍历,而我们可以避免一次。但这可能是另一天的故事,除非您有理由担心非渐近的速度改进。

最后,我们可以遍历distinctWordCounts 来计算字数

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

【讨论】:

  • 这个哈希方法有效!但我试图在没有 map 方法的情况下实现这一目标
【解决方案2】:

听起来您只是想计算每个单词的不同出现次数?如果是这种情况,您可以这样做:

String[] array = {"a", "a", "b", "c", "c", "c", "d", "e", "f", "f"};
Map<String, Long> map = new HashMap<>();

Stream.of(array)
      .distinct()
      .forEach(s -> map.put(s, 
          Stream.of(array)
                .filter(s::equals)
                .count()));

如果你只想要独特的话:

String[] unique = Stream.of(array)
                        .distinct()
                        .toArray(String[]::new);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 2011-10-20
    相关资源
    最近更新 更多