私の目標は、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
ことが一般化することが可能である場合は、これを行う方法?
使用してみてください[ 'regex'](https://stackoverflow.com/documentation/regex/topics)は – TheDarkKnight
は、私はあなたに何を理解していない:あなたはループの中でそれをラップし、それを再利用することができますので、それはきちんとします'一般化'によって意味する。実行時に文字列 'mot 'を変更することを意味しますか? –
初期化せずに任意の単語を検索したい – celia