2017-12-10 25 views
0

ファイルの単語をストリームに読み込もうとしていて、単語 "the"がファイルに現れる回数を数えようとしています。私はストリームだけでこれを行う効率的な方法を理解していないようです。ストリームからファイルから単語を読む

例:ファイルに「川の上に飛び込んだ」というような文が含まれていた場合。出力は、これは私がこれまで試した

public static void main(String[] args){ 

    String filename = "input1"; 
    try (Stream<String> words = Files.lines(Paths.get(filename))){ 
     long count = words.filter(w -> w.equalsIgnoreCase("the")) 
       .count(); 
     System.out.println(count); 
    } catch (IOException e){ 

    } 
} 
+2

これまでに試したことのコードサンプルをご提供ください。そうすれば、私たちはより効果的にあなたを助けることができます。 – Ivonet

答えて

0

あなたは、この目的のために、JavaのStreamTokenizerを使用することができるものである2

だろう。

import java.io.ByteArrayInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.StreamTokenizer; 
import java.io.InputStreamReader; 
import java.nio.charset.StandardCharsets; 

public class Main { 

    public static void main(String[] args) throws IOException { 
     long theWordCount = 0; 
     String input = "The boy jumped over the river."; 
     try (InputStream stream = new ByteArrayInputStream(
      input.getBytes(StandardCharsets.UTF_8.name()))) { 
     StreamTokenizer tokenizer = 
      new StreamTokenizer(new InputStreamReader(stream)); 
      int tokenType = 0; 
      while ((tokenType = tokenizer.nextToken()) 
       != StreamTokenizer.TT_EOF) { 
       if (tokenType == StreamTokenizer.TT_WORD) { 
        String word = tokenizer.sval; 
        if ("the".equalsIgnoreCase(word)) { 
         theWordCount++; 
        } 
       } 
      } 
     } 
     System.out.println("The word 'the' count is: " + theWordCount); 
    } 
} 
0

ジャストライン名はラインない言葉のFiles.linesを返すストリームを示唆しています。あなたは言葉を反復処理したい場合は、あなたが本当にあなたが各ラインを分割することができますストリームを使用して、それらの単語にあなたのストリームをマッピングしたい場合は私、あなたは

Scanner sc = new Scanner(new File(fileLocation)); 
while(sc.hasNext()){ 
    String word = sc.next(); 
    //handle word 
} 

ようScannerを使用することができます

try (Stream<String> lines = Files.lines(Paths.get(filename))){ 
    long count = lines 
      .flatMap(line->Arrays.stream(line.split("\\s+"))) //add this 
      .filter(w -> w.equalsIgnoreCase("the")) 
      .count(); 
    System.out.println(count); 
} catch (IOException e){ 
    e.printStackTrace();//at least print exception so you would know what wend wrong 
} 

ところであなたはshouldn空のキャッチブロックを残しておかないと、少なくとも例外を出力して投げて問題の詳細を知りました。

+0

.splitコマンドの正規表現は、段落間の改行などの改行文字に沿って分割されますか? –

+0

@AddisonWaegeおそらく。 '\ s'は広い範囲の空白を表し、通常この種のタスクには十分です。それを試してみてください。 – Pshemo

0

ストリームリーダーを使用して単語の数を計算します。

関連する問題