2012-03-14 4 views
1

ここでは、コードです:。スキャナを使用してファイルとその数の単語のストア出現箇所、(Java)の

 Scanner scan = new Scanner(new FileReader ("C:\\mytext.txt")); 
     HashMap<String, Integer> listOfWords = new HashMap<String, Integer>(); 

     while(scan.hasNextLine()) 
     { 
      Scanner innerScan = new Scanner(scan.nextLine()); 
      boolean wordExistence ; 
      while(wordExistence = innerScan.hasNext()) 
      { 
       String word = innerScan.next(); 
       int countWord = 0; 
       if(!listOfWords.containsKey(word)){ already 
        listOfWords.put(word, 1); 
       }else{ 
        countWord = listOfWords.get(word) + 1; 
        listOfWords.remove(word); 
        listOfWords.put(word, countWord); 
       } 
      } 
     } 

     System.out.println(listOfWords.toString()); 

問題がある、私の出力は次のように言葉が含まれています

document.Because=1 document.This=1 space.=1は、

このフルストップを処理するにはどうすればよいですか?(さらに問題が発生する場合は、疑問符や感嘆符などの文章ターミネータが問題になると思いますnマーク)。

答えて

2

Scanner APIのクラスノート、特に空白以外の区切り文字の使用に関する段落を見てください。

2

Scannerは、任意の空白をデフォルト区切り文字として使用します。 ScannerインスタンスのuseDelimiter()に電話をかけ、独自の正規表現を区切り文字として使用するように指定することができます。

1

あなたの入力は空白区切り文字を使用するだけでなく、.質問/感嘆符だけではなく、分割したい場合は、Patternを定義し、useDelimiterdoc)を使用して、スキャナにそれを適用する必要があります。

1

スピードの最適化のために、次の答えを試してみてください。

final Pattern WORD = Pattern.compile("\\w+"); 
    while(scan.hasNextLine()) 
    { 
     Scanner innerScan = new Scanner(scan.nextLine()); 
     while(innerScan.hasNext(WORD)) 
     { 
      String word = innerScan.next(WORD); 
      if(!listOfWords.containsKey(word)){ 
       listOfWords.put(word, 1); 
      }else{ 
       int countWord = listOfWords.get(word) + 1; 
       //listOfWords.remove(word); 
       listOfWords.put(word, countWord); 
      } 
     } 
    } 
関連する問題