【发布时间】: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