눈가락
[JAVA] directory 내 모든 파일의 글자 빈도수 계산하기
눈가락
2021. 2. 8. 20:28
가령 /home/eye/dir 위치 내에 a.txt, b.txt, c.txt 가 있다고 하자.
위의 세 개의 파일들을 순서대로 읽고,
파일 내의 글자들의 빈도수를 계산하는 코드를 만들어본다.
위의 코드는 공백을 기준으로 단어들을 카운트하고,
아래 코드는 글자 하나하나를 기준으로 카운트한다.
<공백 기준으로 단어 카운트>
import java.io.*;
import java.util.*;
public class main {
static TreeMap<String, Integer> map;
static String dir = "/home/eye/temp/java/";
public static void main(String[] args) {
map = new TreeMap<>();
for (File info : new File(dir).listFiles()) {
if (info.isFile()) {
read(info.getName());
}
}
}
private static void read(String name){
if(!name.equals("a")) return;
try{
File file = new File(dir+name);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = new String();
while((line=br.readLine())!=null){
wordcount(line);
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("K:' " + entry.getKey() + " '\tV: " + entry.getValue());
}
br.close();
fr.close();
}catch(Exception e){
System.out.println(e);
}
}
private static void wordcount(String word){
String[] splits = word.split("\\s");
for(String split : splits){
Integer num = map.get(split);
if(num==null) num = 0;
map.put(split, num+1);
}
}
}
<글자 하나하나 카운트>
import java.io.*;
import java.util.*;
public class main {
static TreeMap<String, Integer> map;
static String dir = "/home/eye/temp/java/";
public static void main(String[] args) {
map = new TreeMap<>();
for (File info : new File(dir).listFiles()) {
if (info.isFile()) {
read(info.getName());
}
}
}
private static void read(String name){
if(!name.equals("a")) return;
try{
File file = new File(dir+name);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = new String();
while((line=br.readLine())!=null){
wordcount(line);
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("K:' " + entry.getKey() + " '\tV: " + entry.getValue());
}
br.close();
fr.close();
}catch(Exception e){
System.out.println(e);
}
}
private static void wordcount(String word){
for(int i=0; i<word.length(); i++){
String s = String.valueOf(word.charAt(i));
if(s.equals("\\s")) continue;
Integer num = map.get(s);
if(num==null) num = 0;
map.put(s, num+1);
}
}
}