0

Java ScannerhasNextメソッドを使用しようとしましたが、奇妙な結果が得られました。多分私の問題は非常に明白ですが、なぜこの単純な単純な表現が次の"[a-zA-Z']+"ような単語に対して機能しないのですか:「points.anything,supervisor」. 私もこれを試し"[\\w']+"ました。

public HashMap<String, Integer> getDocumentWordStructureFromPath(File file) {
    HashMap<String, Integer> dictionary = new HashMap<>();
    try {
        Scanner lineScanner = new Scanner(file);
        while (lineScanner.hasNextLine()) {
            Scanner scanner = new Scanner(lineScanner.nextLine());
            while (scanner.hasNext("[\\w']+")) {
                String word = scanner.next().toLowerCase();
                if (word.length() > 2) {
                    int count = dictionary.containsKey(word) ? dictionary.get(word).intValue() + 1 : 1;
                    dictionary.put(word, new Integer(count));
                }
            }
            scanner.close();
        }
        //scanner.useDelimiter(DELIMITER);
        lineScanner.close();

        return dictionary;

    } catch (FileNotFoundException e) { 
        e.printStackTrace();
        return null;
    }   
}
4

1 に答える 1

1

[^a-zA-z]+文字ではないものをすべて区切る必要があるため、正規表現は次のようになります。

// previous code...
Scanner scanner = new Scanner(lineScanner.nextLine()).useDelimiter("[^a-zA-z]+");
    while (scanner.hasNext()) {
        String word = scanner.next().toLowerCase();
        // ...your other code
    }
}
// ... after code

EDIT-- hasNext(String) メソッドで動作しないのはなぜですか??

この行:

Scanner scanner = new Scanner(lineScanner.nextLine());

実際に行うことは、whitespce パターンをコンパイルすることです。たとえば、このテスト行"Hello World. A test, ok."がある場合、このトークンが配信されます。

  • こんにちは
  • 世界。
  • テスト、
  • わかった。

次にscanner.hasNext("[a-ZA-Z]+")、スキャナーに問い合わせている場合if there is a token that match your pattern、この例ではtrue、最初のトークンについて次のように述べています。

  • こんにちは (これは、指定したパターンに一致する最初のトークンであるため)

次のトークン ( World. )it doesn't match the patternでは単純failscanner.hasNext("[a-ZA-Z]+")返さfalseれるため、文字以外の文字が前にある単語では機能しません。わかりますか?

今...これが役立つことを願っています。

于 2013-04-07T17:48:24.397 に答える