1

質問1:

キーワードの頻度をカウントしようとしていますが、私のコードは、キーワードを含む単語もカウントすることを除いて機能します (たとえば、「カウント」を検索すると、「アカウント」のような単語もカウントされます)。誰かがこれを解決する方法を知っていますか?

質問2:

また、テキスト内の一意の単語の数をカウントしたい (つまり、繰り返される単語を 1 回だけカウントする)。これを達成する方法もわかりません。私のコードでは、合計単語数しかわかりません。

これが私のコードです:

import java.util.Scanner;


public class Text_minining {

/**
 * @param args
 */
public static void main(String[] args) {

    //Prompt the user for the search word
    System.out.print("enter a search word: ");
    //Get the user's search word input
    Scanner keywordScanner = new Scanner(System.in);
    String keyword = keywordScanner.nextLine();
    keyword = keyword.toLowerCase();

    //Prompt the user for the text
    System.out.println("Enter a string of words (words separated by single spaces or tabs): ");
    //Get the user's string input
    Scanner userInputScanner = new Scanner(System.in);
    String userInput = userInputScanner.nextLine();
    userInput = userInput.toLowerCase();

    int keywordCount = 0, wordCount = 0;
    int lastIndex = 0;

    while(lastIndex != -1){
        lastIndex = userInput.indexOf(keyword,lastIndex);
        if(lastIndex != -1){
            keywordCount ++;
            lastIndex = keyword.length() + lastIndex;
        }
    }

    boolean wasSpace=true;
    for (int i = 0; i < userInput.length(); i++) 
    {
        if (userInput.charAt(i) == ' ') {
            wasSpace=true;
        }
        else{
            if(wasSpace == true) wordCount++;
            wasSpace = false;
            }
    }

    //Print the results to the screen
    System.out.println("-------");
    System.out.println("Good, \"" + keyword + "\"appears in the text and the word count is " + keywordCount);
    System.out.println("The total number of unique words in the text is " + wordCount);


    System.exit(0);
}
    }
4

4 に答える 4

1

同意。分割を使用して配列を作成すると、使用できます

(new HashSet(Arrays.asList(yourArray))).size(); 

カウントを見つける

于 2013-10-04T18:16:29.377 に答える