【问题标题】:String frequency search not finding all words字符串频率搜索未找到所有单词
【发布时间】:2018-11-27 23:22:45
【问题描述】:

我正在尝试实现一个字符串频率搜索算法,它解析jokes.txt 文件并获取测试中每个唯一单词的出现次数。 该算法应考虑区分大小写并使“a”和“A”都唯一。截至目前,该算法似乎跳过了测试中第一次出现的“a”以及后来的许多其他单词。

此外,words 数组包含文本中的每个单词。不知何故,(!isDuplicate) 条件中的循环跳过了“a”并且不会增加count

jokes.txt

I wondered why the baseball was getting bigger.
Then it hit me.

Police were called to a day care
where a 3-yr-old was resisting a rest.
...

WordCounter.java

import java.util.*;
import java.io.FileNotFoundException;
import java.io.FileInputStream;

public class WordCounter {
    ArrayList<String> words = new ArrayList<String>();

    //prints number of words in the  file
    public void numOfWords(Scanner key1) {
        int counter = 1;
        while(key1.hasNext()) {
            words.add(key1.next().replaceAll("[^a-zA-Z]", ""));

        }
    }

    //Takes word as parameter and returns frequency of that word
    public void frequencyCounter(Scanner key1) {
        ArrayList <String> freqWords = new ArrayList<String>();
        int count = 1;
        int counter = 1;

        for(int i = 0; i < words.size(); i++){
            boolean isDuplicate = false;
            for (String s: freqWords){
                if (s.contains(words.get(i).trim()))
                    isDuplicate =true;
            }

            if (!isDuplicate){

                for(int j = i + 1; j < words.size(); j++){
                    if(words.get(i).equals(words.get(j))){
                        count++;
                    }
                }
                freqWords.add(count + "-" + words.get(i));
                Collections.sort(freqWords, Collections.reverseOrder());
                count = 1;     
            }
        }

        for(int i = 0; i < freqWords.size(); i++) {
            System.out.print((i+1) + "       ");
            System.out.println(freqWords.get(i));
        }
    }

}

【问题讨论】:

  • 请更具体。
  • @shmosel 刚刚做到了
  • 还不清楚是什么问题。告诉我们实际发生的事情,而不是您想象的代码在做什么。
  • @shmosel 我运行调试器无时间来跟踪正在发生的事情,并跳过了“a”。我不知道这是什么原因。
  • 跳过了哪里?什么时候?从何而来?

标签: java string text frequency word-frequency


【解决方案1】:

您确定重复的逻辑有点不正确:

        boolean isDuplicate = false;
        for (String s: freqWords){
            if (s.contains(words.get(i).trim()))
                isDuplicate =true;
        }

如果 words.get(i) 是“a”并且 s 是“apple”,这将使 isDuplicate 为 true,因为 apple 包含“a”。检查 s 中的单词是否与 words.get(i) 完全匹配。

【讨论】:

    【解决方案2】:

    只需编辑我的错误答案:

    但可能是 contains() 造成了问题,因为 API 告诉我们它在字符串中搜索字符序列。这意味着您基本上是在每个单词中搜索 Charsequenz“a”并告诉它是重复的。所以它会将“day”计数为一个,因为您正在搜索“a”

    在我看来,使用 HashMap 搜索重复项会更好,而且速度会更快。你可以数一数这些值有多少。

    【讨论】:

    • ^ 是否定的。
    • 编辑为我认为您正在寻找的解决方案
    猜你喜欢
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 2011-12-27
    相关资源
    最近更新 更多