想要计算 Java 中字符串的出现次数

Want to count occurances of Strings in Java

所以我有一个 .txt 文件,我正在调用它

String[] data = loadStrings("data/data.txt");

文件已经排序,基本上看起来像:

Animal
Animal
Cat
Cat
Cat
Dog

我想创建一种算法来计算 java 中的排序列表,而不使用任何库(如 Multisets)或不使用 Maps/HashMaps。到目前为止,我已经设法让它打印出出现次数最多的单词,如下所示:

ArrayList<String> words = new ArrayList();

int[] occurrence = new int[2000];
Arrays.sort(data);

for (int i = 0; i < data.length; i ++ ) {
words.add(data[i]);     //Put each word into the words ArrayList
}
for(int i =0; i<data.length; i++) {
 occurrence[i] =0;
 for(int j=i+1; j<data.length; j++) {
   if(data[i].equals(data[j])) {
     occurrence[i] = occurrence[i]+1;
   }
 }
}
int max = 0;
String most_talked ="";
for(int i =0;i<data.length;i++) {
  if(occurrence[i]>max) {
    max = occurrence[i];
    most_talked = data[i];
  }
 }
 println("The most talked keyword is " + most_talked + " occuring " + max + " times.");

我想要的不仅仅是获得出现次数最多的词,也许是前 5 名或前 10 名。 希望这已经足够清楚了。感谢阅读

如果你不能使用 Guava 的 Multiset,那么你可以自己实现一个等效的。基本上,您只需要创建一个 Map<String, Integer>,它会跟踪每个单词(键)的计数(值)。这意味着改变这个

ArrayList<String> words = new ArrayList<String>();
// ...
for (int i = 0; i < data.length; i ++ ) {
  words.add(data[i]);     //Put each word into the words ArrayList
}

进入这个:

Map<String, Integer> words = new HashMap<String>();
// ...
for (String word : data) {
  Integer count = words.get(word);
  words.put(word, (count != null : count.intValue() + 1 ? 1));
}

填满地图后,sort it by the values

如果您也不能使用 Map,您可以执行以下操作:

首先,为您的字数创建一个包装器class:

public class WordCount implements Comparable<WordCount> {
    private String word;
    private int count;

    public WordCount(String w, int c) {
      this.word = w;
      this.count = c;
    }

    public String getWord() {
      return word;
    }

    public int getCount() {
      return count;
    }

    public void incrementCount() {
      count++;
    }                 

    @Override
    public int compareTo(WordCount other) {
      return this.count - other.count;
    }
}

然后,更改代码以在列表中存储 WordCount 个实例(而不是 String 个):

ArrayList<WordCount> words = new ArrayList<WordCount>();
// ...
for (String word : data) {
    WordCount wc = new WordCount(word, 1);
    boolean wordFound = false;

    for (WordCount existing : words) {
        if (existing.getWord().equals(wc.getWord())) {
            existing.incrementCount();
            wordFound = true;
            break;
        }
    }

    if (!wordFound) {
        words.add(wc);
    }
}

最后,填充 List 后,只需使用 Collections.sort() 对其进行排序。这很容易,因为值对象实现 Comparable:

Collections.sort(words, Collections.reverseOrder());

你可以尝试像这样简单的东西..

int count = 0;

for( int i = 0; i < words.size(); i++ ){
    System.out.printf("%s: ", words.get( i ));
    for( int j = 0; j < words.size(); j++ ) {
        if( words.get( i ).equals( words.get( j ) ) )
            count++;
    }                                               
    System.out.printf( "%d\n", count );
}

既然你说你不想使用某种数据结构,我认为你可以做这样的事情,但它不是高性能的。 我通常更喜欢存储索引而不是值。

ArrayList<String> words = new ArrayList();

int[] occurrence = new int[2000];
Arrays.sort(data);


int nwords = 0;
occurrence[nwords]=1;
words.add(data[0]);        
for (int i = 1; i < data.length; i ++ ) {
    if(!data[i].equals(data[i-1])){ //if a new word is found
        words.add(data[i]);         //put it into the words ArrayList
        nwords++;                   //increment the index
        occurrence[nwords]=0;       //initialize its occurrence counter
    }
    occurrence[nwords]++;           //increment the occurrence counter
}

int max;
for(int k=0; k<5; k++){  //loop to find 5 times the most talked word
  max = 0;               //index of the most talked word
  for(int i = 1; i<words.size(); i++) { //for every word
    if(occurrence[i]>occurrence[max]) { //if it is more talked than max
      max = i;                          //than it is the new most talked
    }
  }
  println("The most talked keyword is " + words.get(max) + " occuring " + occurence[max] + " times.");
  occurence[max]=0;
}

每次找到出现次数较多的值时,我都会将他的出现次数计数器设置为0,然后重复数组,重复5次。