2017-06-06 24 views
1

私の目標は、jsonファイル内に単語iを含む行の数を返す関数(Ri)をプログラムすることです。私は初期化したが、その後、私は一般化する方法を知らない。 これは私のスタートコードです:Javaでjsonファイル内の単語を検索する方法

public class rit { 
private static final String filePath = "D:\\c4\\11\\test.json"; 
    public static void main(String[] args) throws FileNotFoundException, ParseException, IOException { 
     try{ 
      InputStream ips=new FileInputStream(filePath); 
      InputStreamReader ipsr=new InputStreamReader(ips); 
      BufferedReader br=new BufferedReader(ipsr); 
      String ligne; 
       String mot="feel"; 
       int i=1; 
       // nombre de lignes totales contenant le terme 
       int nbre=0; 
      while ((ligne=br.readLine())!=null){ 

      try { 
      // read the json file 
       JSONParser jsonParser = new JSONParser(); 
      JSONObject jsonObject = (JSONObject) jsonParser.parse(ligne); 

       // get a number from the JSON object 
      String text = (String) jsonObject.get("text"); 

         if (text.contains(mot)){ 
         nbre++; 
         System.out.println("Mot trouvé a la ligne " + i); 
         i++; 

         } 

     } catch (ParseException ex) { 
      ex.printStackTrace(); 
     } catch (NullPointerException ex) { 
      ex.printStackTrace(); 
     }} 

       System.out.println("number of lines Which contain the term: " +nbre); 
    br.close(); 
}  
catch (Exception e){ 
    System.out.println(e.toString()); 
}}} 

、出力は次のとおりです。

Mot trouvé a la ligne 1 
Mot trouvé a la ligne 2 
number of lines Which contain the term: 2 

ことが一般化することが可能である場合は、これを行う方法?

+0

使用してみてください[ 'regex'](https://stackoverflow.com/documentation/regex/topics)は – TheDarkKnight

+0

は、私はあなたに何を理解していない:あなたはループの中でそれをラップし、それを再利用することができますので、それはきちんとします'一般化'によって意味する。実行時に文字列 'mot 'を変更することを意味しますか? –

+0

初期化せずに任意の単語を検索したい – celia

答えて

0

String args[]public static void main(String[] args)は、入力パラメータである。したがって、java rit.class feelを実行する場合、args[feel]となります。

public static void main(String[] args) { 
    if(args.length != 2){ 
     // crash the application with an error message 
     throw new IllegalArgumentException("Please enter $filePath and $wordToFind as input parameters"); 
    } 
    String filePath = args[0]; 
    String mot = args[1]; 
    System.out.println("filePath : "+filePath); 
    System.out.println("mot : "+mot); 
} 

そうするもう一つの方法は、ユーザの入力を待つことです:あなたは、あなたのプログラムを作ることができる

は、これらの入力引数のワード(とさえfilePathに)を期待しています。

public static void main(String[] args) { 
    Scanner scanner = new Scanner(System.in); // used for scanning user input 
    while(true){ 
     System.out.println("please enter a word : "); 
     String mot = scanner.nextLine(); // wait for user to input a word and enter 
     System.out.println("mot is : "+mot); 
    } 
} 
+0

私はこれを試します。ありがとうございました。 – celia

+0

私の問題を解決してくれてありがとう。 – celia

+0

私は別の質問を持っています。私は、同じ日付に用語iを含む魔法使いの数を返したいと思っています。異なる日を持つつぶやきを含むjsonファイルがあることを知っています。どうやって進める? – celia

関連する問題