24.03.23

서린·2024년 3월 23일

혼자개발

목록 보기
75/82

인덱스 메이커

  • 입력으로 하나의 텍스트 파일을 읽는다
  • 텍스트 파일에 등장하는 모든 단어들의 목록을 만들고 각 단어가 텍스트 파일에 등장하는 횟수를 센다 (단어의 개수는 100,000개 이하라고 가정한다)
  • 사용자가 요청하면 단어 목록을 하나의 파일로 저장한다
  • 사용자가 단어를 검색하면 그 단어가 텍스트 파일에 몇 번 등장하는 지 출력한다
public class Code22 {

	static String [] words = new String [100000]; // 단어들의 목록을 저장할 배열
	static int [] count = new int [100000]; // 단어의 등장 횟수
	static int n = 0; // 저장된 단어의 개수
	
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		while (true) { // 무한루프
			System.out.print("$ ");
			String command = scan.next();
			if (command.equals("read")) {
				String fileName = scan.next();
				makeIndex(fileName);
				
			} else if (command.equals("find")) {
				String str = scan.next();
				int index = findWord(str);
				if (index != -1) {
					System.out.println("단어 " + words[index] + "는 " + count[index] + "번 언급되었습니다");
				} else {
					System.out.println("단어 " + str + "는 " + "언급되지 않았습니다");
				}
			} else if (command.equals("saveas")) {
				String fileName = scan.next();
				saveAs(fileName);
			} else if (command.equals("exit")) {
				break;
			}
		}
		scan.close();
		
		for (int i = 0; i < n; i++) {
			System.out.println(words[i] + " "  + count[i]);
		}
	}//
	
	static void saveAs(String fileName) {
		try {
			PrintWriter outFile = new PrintWriter(new FileWriter(fileName));
			for (int i = 0; i < n; i++) {
				System.out.println(words[i] + " "  + count[i]);
			}
			
			outFile.close();
		} catch (IOException e) {
			System.out.println("save failed");
			return;
		}
		
	}
	
	static void makeIndex(String fileName) {
		try {
			Scanner inFile = new Scanner(new File(fileName));
			while (inFile.hasNext()) { //hasnext가 true인 동안에 while문을 돈다
				String str = inFile.next();
				
				addWord(str);
				
			}
			inFile.close();
		} catch (FileNotFoundException e) {
			System.out.println("No file");
			return;
		}
	}
	
	static void addWord(String str) {
		int index = findWord(str);  // 단어 못 찾으면 return -1
		if (index != -1) { // 단어 찾았다면 = words[index] == str일 때
			count[index]++;
		} else { // 단어 못 찾았다면 == 새로운 단어가 등장했다는 뜻
			words[n] = str; 
			count[n] = 1;
			n++;
		}
	}
	
	static int findWord(String str) {
		for (int i = 0; i < n; i++) {
			if (words[i].equalsIgnoreCase(str)) { // 대소문자 구별 안함
				return i;
			}
		}
		return -1; // 찾는 단어가 없을 때
	}
}//

출력값
$ read sample.txt
$ find mapper
단어 mapper는 2번 언급되었습니다
$ find debug
단어 debug는 언급되지 않았습니다

0개의 댓글