2014-04-08 45 views
0

我想從大型文本文件中實現字符串匹配任務。 1.替換所有非字母數字字符 2.計算文本文件中特定術語的編號。例如,匹配項「湯姆」。匹配不區分大小寫。我應該算「湯姆」這個術語。但是明天這個詞不應該被計算在內。從大文本文件中匹配java字符串問題

code template one: 
    try { 
      in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)); 
     } catch (FileNotFoundException e1) { 
      System.out.println("Not found the text file: "+inputFile); 
     } 
    Scanner scanner = null; 
    try { 
     while ((line = in.readLine())!=null){ 
       String newline=line.replaceAll("[^a-zA-Z0-9\\s]", " ").toLowerCase(); 
       scanner = new Scanner(newline); 
       while (scanner.hasNext()){ 
         String term = scanner.next(); 
        if (term.equalsIgnoreCase(args[1])) 
        countstr++; 
       } 
     } 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 

code template two: 
    try { 
     in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)); 
     } catch (FileNotFoundException e1) { 
      System.out.println("Not found the text file: "+inputFile); 
     } 
    Scanner scanner = null; 
    try { 
     while ((line = in.readLine())!=null){ 
       String newline=line.replaceAll("[^a-zA-Z0-9\\s]", " ").toLowerCase(); 
       String[] strArray=newline.split(" ");//split by blank space 
         for (int =0;i<strArray.length;i++) 
           if (strArray[i].equalsIgnoreCase(args[1])) 
             countstr++; 
       } 
     } 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 

通過運行兩個代碼,我得到了不同的結果,掃描儀看起來像得到正確的one.But對於大的文本文件,掃描儀的運行速度比後者更慢。任何人都可以告訴我原因並提供更有效的解決方案。

回答

1

在你第一次接觸。你不需要使用兩臺掃描儀。帶「」的掃描儀不適合大型產品線。

你的行已經轉換爲小寫。所以你只需要在外面做一次小寫字母。而做等於在循環

或者讓行

String key = String.valueOf(".*?\\b" + "Tom".toLowerCase() + "\\b.*?"); 
     Pattern p = Pattern.compile(key); 
     word = word.toLowerCase().replaceAll("[^a-zA-Z0-9\\s]", ""); 
     Matcher m = p.matcher(word); 
     if (m.find()) { 
      countstr++; 
     } 

個人而言,我會選擇大文件的BufferedReader的方法。

String key = String.valueOf(".*?\\b" + args[0].toLowerCase() + "\\b.*?"); 
     Pattern p = Pattern.compile(key); 
     try (final BufferedReader br = Files.newBufferedReader(inputFile, 
        StandardCharsets.UTF_8)) { 
       for (String line; (line = br.readLine()) != null;) { 
        // processing the line. 
        line = line.toLowerCase().replaceAll("[^a-zA-Z0-9\\s]", ""); 
        Matcher m = p.matcher(line); 
        if (m.find()) { 
         countstr++; 
        }   
       } 
     } 

在Java中給出示例7.如果需要更改!