2013-08-06 2 views
0

그래서 나는 이것을 약간의 시간 동안 작동 시키려고 노력했습니다. 필자가 프로그래머가 아니라고 말하면서이 사실을 알리겠습니다. 최근에 내가 취한 취미는 더 많습니다. 두 줄의 텍스트 파일을 줄 단위로 검색하려고했습니다. 하나의 단어는 한 줄에 하나씩 약 10 개, 다른 단어에는 한 줄에 하나 더 많은 단어가 있습니다. 내가 좋아하는 것은 내 프로그램이 더 작은 텍스트 파일에있는 각 단어가 더 큰 단어에 몇 번이나 나왔는지 말하는 것입니다. 지금까지 내가 무엇을 가지고 :하나의 텍스트 파일을 사용하여 다른 텍스트 파일을 검색합니다.

import java.util.Scanner; 
    import java.io.File; 
    import java.util.regex.Pattern; 

    public class StringSearch 
    { 

    public static void main (String args[]) throws java.io.IOException 
     { 
    int tot = 0; 
    Scanner scan = null; 
    Scanner scan2 = null; 
    String str = null; 
    String str2 = null; 


    File file = new File("C:\\sample2.txt"); 
    File file2 = new File("C:\\sample3.txt"); 
    scan = new Scanner(file); 
    scan2 = new Scanner(file2); 
     while (scan.hasNextLine()) 
     { 
     str = scan.nextLine(); 
     tot = 0; 
      while (scan2.hasNextLine()) 
      { 
       str2 = scan2.nextLine(); 
        if(str.equals(str2)) 
        { 
       tot++; 
        } 
      } 
    System.out.println("The String = " + str + " and it occurred " + tot + " times"); 
     } 

    } 
    } 

잘 모르겠어요 왜이 작동하지 않습니다. 첫 번째 텍스트 파일의 첫 번째 단어를 읽은 다음 두 번째 텍스트 파일에 나타나는 횟수를 계산하지만 첫 번째 파일의 두 번째 단어를 중지하고 이동하지 않습니다. 나는 그것이 의미가 있기를 바랍니다. 루프가 생각하는 동안 두 번째로 뭔가 잘못 됐습니다. 그러나 나는 무엇을 모릅니다.

그래서 도움을 주시면 대단히 감사하겠습니다. 이 작업을 수행하고 앞으로 더 복잡한 프로젝트로 이동하기를 바라고 있습니다. 어딘가에서 시작해야할까요?

건배 얘들 아

+0

첫 번째 파일의 모든 단어를 배열에로드하는 경우 두 번째 파일에서 읽고 배열의 내용과 비교하면됩니다. 단어의 양은 메모리를 많이 차지하지 않을 정도로 작으며 한 파일 만 취급합니다. –

+0

참고 : 쉘을 사용하여 :'fgrep -f sample2.txt sample3.txt' –

답변

0

당신은 스캐너에서 스캐너를 사용하고 있는지 당신이에서 실행하는 문제입니다. 현재 스캐너에 중첩되어있는 방식으로 한 스캐너가 첫 번째 단어의 전체 텍스트 파일을 완전히 읽을 수 있지만 처음 실행 한 후에는 이미 전체 파일을 읽었으므로 scan2.hasNextLine()에 대해서는 true를 반환하지 않습니다.

remyabel이 말한 것은 원하는 것을 얻기위한 더 좋은 방법입니다. 작은 파일의 모든 단어를 포함하는 배열을 만들어야합니다.이 배열은 다른 파일의 단어를 반복 할 때마다 반복됩니다. 또한 해시 맵과 같은 것을 사용할 수 있도록 각 단어의 횟수를 추적하기 위해 무언가를 만들어야합니다.

그것은이의 라인을 따라 뭔가를 보일 것이다

Scanner scan = null; 
Scanner scan2 = null; 
String str = null; 
String str2 = null; 


File file = new File("C:\\sample2.txt"); 
File file2 = new File("C:\\sample3.txt"); 
scan = new Scanner(file); 
scan2 = new Scanner(file2); 
//Will contain all of your words to check against 
ArrayList<String> dictionary = new ArrayList<String>(); 
//Contains the number of times each word is hit 
HashMap<String,Integer> hits = new HashMap<String, Integer>(); 
while(scan.hasNextLine()) 
{ 
    str = scan.nextLine(); 
    dictionary.add(str); 
    hits.put(str, 0); 
} 
    while (scan2.hasNextLine()) 
     { 
      str2 = scan2.nextLine(); 
      for(String str: dictionary) 
      { 
       if(str.equals(str2)) 
       { 
        hits.put(str, hits.get(str) + 1); 
       } 
      } 
     } 
    for(String str: dictionary) 
    { 
     System.out.println("The String = " + str + " and it occurred " + hits.get(str) + " times"); 
    } 
} 
0

은 버퍼 리더를 작성하고 <String, Integer>의지도로 파일을 읽어

String filename = args[0]; 
BufferedReader words = new BufferedReader(new FileReader(FILENAME)); 
Map<String, Integer>m = new HashMap<String, Integer>(); 
for(String word: words.readLine()){ 
    if(word!=null && word.trim().length()>0) { 
     m.add(String, 0); 
    } 
} 

가 그런 단어 목록을 읽고 증가 다음을 찾을 때마다지도 값 :

String filename = args[1]; 
BufferedReader listOfWords = new BufferedReader(new FileReader(FILENAME2)); 
for(String word: listOfWords.readLine()){ 
    if(word!=null && word.trim().length()>0) { 
     if(m.get(word)!=null){ 
      m.add(word, m.get(word) + 1); 
     } 
    } 
}  

그런 다음 결과를 인쇄하십시오.

for(String word: map.keys()){ 
    if(map.get(word)>0){ 
     System.out.println("The String = " + word + " occurred " + map.get(word) + " times"); 
    } 
} 
0

중첩 루프를 사용하면 첫 번째 단어의 모든 단어에 대해 두 번째 파일을 검색 할 수 있습니다. 이것은 매우 비효율적이다. HashMap에 첫 번째 파일을로드하는 것이 좋습니다.

빠른 검색을 활용할뿐만 아니라 쉽게 발생 횟수를 업데이트 할 수 있습니다. 말할 필요도없이, 두 번째 파일을 한 번만 스캔하면 첫 번째 파일에있는 복제본은 자동으로 무시됩니다 (결과는 동일합니다).

Map<String, Integer> wordCounts = new HashMap<String, Integer>(); 

Scanner scanner = new Scanner("one\nfive\nten"); 
while (scanner.hasNextLine()) { 
    wordCounts.put(scanner.nextLine(), 0); 
} 
scanner.close(); 

scanner = new Scanner("one\n" + // 1 time 
         "two\nthree\nfour\n" + 
         "five\nfive\n" + // 2 times 
         "six\nseven\neight\nnine\n" + 
         "ten\nten\nten"); // 3 times 

while (scanner.hasNextLine()) { 
    String word = scanner.nextLine(); 
    Integer integer = wordCounts.get(word); 
    if (integer != null) { 
     wordCounts.put(word, ++integer); 
    } 
} 
scanner.close(); 

for (String word : wordCounts.keySet()) { 
    int count = wordCounts.get(word); 
    if (count > 0) { 
     System.out.println("'" + word + "' occurs " + count + " times."); 
    } 
} 

출력 :

'ten' occurs 3 times. 
'five' occurs 2 times. 
'one' occurs 1 times. 
0

그것의 단순한 논리 문제 ..에서 System.out.println 아래

추가 다음 문 = 새로운 스캐너

SCAN2 (file2);

+0

이것은 어떻게 OP의 질문을 해결합니까? – UditS

관련 문제