디렉토리의 파일 수를 먼저 계산 한 다음 각 파일에 단어 수를 할당하는 작업을 수행하려고합니다. 파일 수는 괜찮지 만 강사가 간단한 단어 수를 계산하는 클래스에서 준 코드를 변환하는 데 어려움을 겪고 있습니다. 또한, 나는 단어를 계산하기 위해 각 파일을 볼 적절한 코드를 찾지 못하는 것 같습니다 (특정 텍스트가 아닌 "일반"을 찾으려고 노력하지만 특정 텍스트 파일을 사용하여 프로그램을 테스트하려고합니다) .텍스트 파일에서 자바 8 스타일의 단어 수를 계산하는 방법
primes.txt
but
are
sometimes
sense
refrigerator
make
haiku
dont
they
funny
word length: 1 ==> {but=1, are=1, sometimes=1, sense=1, refrigerator=1, make=1, haiku=1, dont=1, they=1, funny=1}
.....
Count 11 files:
을 나는 두 개의 클래스를 사용하고 있습니다 : 단어 수 및 FileCatch8
단어 수 :
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
import java.util.Map;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
/**
*
* @author
*/
public class WordCount {
/**
*
* @param filename
* @return
* @throws java.io.IOException
*/
public Map<String, Long> count(String filename) throws IOException {
//Stream<String> lines = Files.lines(Paths.get(filename));
Path path = Paths.get("haiku.txt");
Map<String, Long> wordMap = Files.lines(path)
.parallel()
.flatMap(line -> Arrays.stream(line.trim().split(" ")))
.map(word -> word.replaceAll("[^a-zA-Z]", "").toLowerCase().trim())
.filter(word -> word.length() > 0)
.map(word -> new SimpleEntry<>(word, 1))
//.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
.collect(groupingBy(SimpleEntry::getKey, counting()));
wordMap.forEach((k, v) -> System.out.println(String.format(k,v)));
return wordMap;
}
}
Count 11 files:
word length: 1 ==> 80
word length: 2 ==> 321
word length: 3 ==> 643
그러나이 대신 출력되고 있는지입니다 : 이것은 의도 된 출력
및 FileCatch :
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author
*/
public class FileCatch8 {
public static void main(String args[]) {
List<String> fileNames = new ArrayList<>();
try {
DirectoryStream<Path> directoryStream = Files.newDirectoryStream
(Paths.get("files"));
int fileCounter = 0;
WordCount wordCnt = new WordCount();
for (Path path : directoryStream) {
System.out.println(path.getFileName());
fileCounter++;
fileNames.add(path.getFileName().toString());
System.out.println("word length: " + fileCounter + " ==> " +
wordCnt.count(path.getFileName().toString()));
}
} catch(IOException ex){
}
System.out.println("Count: "+fileNames.size()+ " files");
}
}
이 프로그램은
합니까를, 새로운 SimpleEntry <> (워드, 1) 1지도 값 각 시간을 설정? –
SimpleEntry를 만들고 SimpleEntry :: getKey를 사용하지 않고도 Function.identity()를 사용할 수 있습니다. 더 간단한 파일 계산을 위해 Files.walk ...를보십시오. – egorlitvinenko
나는 그렇게 생각한다. 그런 식으로하는 것이 잘못 되었습니까? –