2014-04-08 2 views
0

큰 텍스트 파일에서 문자열 일치 작업을 구현하고 싶습니다. 1. 영숫자가 아닌 모든 문자를 바꿉니다. 2. 텍스트 파일에서 특정 용어의 수를 계산합니다. 예를 들어 용어 "tom"과 일치시킵니다. 일치하는 대소 문자를 구분하지 않습니다 .so 용어는 "톰"내가 계산해야합니다. 그러나 내일이라는 용어는 계산해서는 안됩니다. 두 코드를 실행하여큰 텍스트 파일에서 자바 문자열이 일치합니다.

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(); 
    } 

, 나는 다른 결과를 얻을, 스캐너는 권리를 얻을처럼 보인다는 없었나 큰 텍스트 파일, 스캐너는 후자보다 훨씬 더 느리게 실행됩니다. 이유를 말해주고 훨씬 더 효율적인 해결책을 제시 할 수있는 사람.

답변

1

첫 번째 승인시. 스캐너 두 대를 사용할 필요가 없습니다. ""이있는 스캐너는 큰 선에 적합하지 않습니다.

귀하의 회선은 이미 소문자로 변환되었습니다. 그래서 당신은 한 번 밖에 소문자 키를 할 필요가 있습니다. 그리고 이렇게 루프

에 동일 또는 개인적으로 난 큰 파일의 BufferedReader 접근 방식을 선택할 것 라인을

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++; 
     } 

를 얻을.

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++; 
        }   
       } 
     } 

자바 샘플을 보내십시오. 7. 필요한 경우 변경하십시오!

관련 문제