2017-06-06 61 views
1

我的目标是编写一个函数(Ri),该函数返回json文件中包含术语i的行数,为此,我通过查找单词我初始化了,但后来我不知道如何推广。 这是我开始代码:如何使用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

我不明白你意思是'泛化'。你的意思是在运行时改变String'mot'吗? –

+0

我想搜索任何没有初始化的词 – celia

回答

0

String args[] in 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); 
} 

另一种方式做,是为了等待用户输入。它的整洁,因为你可以在一个循环中包并重复使用:

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

我还有一个问题,我想返回在同一日期的女巫包含术语我的行数,知道我有一个包含具有不同日期的推文的json文件。如何进行? – celia