如何计算文本文件中的字数,java 8风格

如何计算文本文件中的字数,java 8风格,java,lambda,java-8,java-stream,word-count,Java,Lambda,Java 8,Java Stream,Word Count,我正在尝试执行一个赋值,该赋值首先计算目录中的文件数,然后给出每个文件中的字数。我得到了文件数,但我很难将我的老师给我的一些代码从一个进行频率计数的类转换为更简单的单词计数。此外,我似乎找不到正确的代码来查看每个文件以计算单词(我试图找到“通用”而不是特定的代码,但我试图使用特定的文本文件测试程序)。这是预期输出: Count 11 files: word length: 1 ==> 80 word length: 2 ==> 321 word length: 3 ==> 64

我正在尝试执行一个赋值,该赋值首先计算目录中的文件数,然后给出每个文件中的字数。我得到了文件数,但我很难将我的老师给我的一些代码从一个进行频率计数的类转换为更简单的单词计数。此外,我似乎找不到正确的代码来查看每个文件以计算单词(我试图找到“通用”而不是特定的代码,但我试图使用特定的文本文件测试程序)。这是预期输出:

Count 11 files:
word length: 1 ==> 80
word length: 2 ==> 321
word length: 3 ==> 643
但是,这是正在输出的内容:

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:
我使用两个类:WordCount和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;
        }
    }
import java.io.IOException;
导入java.nio.file.Files;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.util.AbstractMap.SimpleEntry;
导入java.util.array;
导入java.util.Map;
导入静态java.util.stream.Collectors.counting;
导入静态java.util.stream.Collectors.groupingBy;
/**
*
*@作者
*/
公共类字数{
/**
*
*@param文件名
*@返回
*@抛出java.io.IOException
*/
公共映射计数(字符串文件名)引发IOException{
//streamlines=Files.lines(path.get(filename));
Path=Path.get(“haiku.txt”);
Map wordMap=Files.lines(路径)
.parallel()
.flatMap(line->array.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(groupby(SimpleEntry::getKey,counting());
forEach((k,v)->System.out.println(String.format(k,v));
返回wordMap;
}
}
和文件捕获:

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");

  }
}
import java.io.IOException;
导入java.nio.file.DirectoryStream;
导入java.nio.file.Files;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.util.ArrayList;
导入java.util.List;
/*
*要更改此许可证标题,请在“项目属性”中选择“许可证标题”。
*要更改此模板文件,请选择工具|模板
*然后在编辑器中打开模板。
*/
/**
*
*@作者
*/
公共类文件捕获8{
公共静态void main(字符串参数[]){
列表文件名=新的ArrayList();
试一试{
DirectoryStream DirectoryStream=Files.newDirectoryStream
(path.get(“文件”);
int fileCounter=0;
WordCount wordCnt=新的WordCount();
for(路径:directoryStream){
System.out.println(path.getFileName());
fileCounter++;
添加(path.getFileName().toString());
System.out.println(“字长:+fileCounter+”==>“+
count(path.getFileName().toString());
}
}捕获(IOEX异常){
}
System.out.println(“计数:“+fileNames.size()+”文件”);
}
}
该程序使用具有lambda语法的Java 8流,例如:

Files.lines(Paths.get(file))
    .flatMap(line -> Arrays.stream(line.trim().split(" ")))
    .map(word -> word.replaceAll("[^a-zA-Z]", "").toLowerCase().trim())
    .filter(word -> !word.isEmpty())
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
文件计数:

Files.walk(Paths.get(file), Integer.MAX_VALUE).count();
Files.walk(Paths.get(file)).count();

在我看来,使用Java 8计算文件中单词的最简单方法是:

Long wordsCount = Files.lines(Paths.get(file))
    .flatMap(str->Stream.of(str.split("[ ,.!?\r\n]")))
    .filter(s->s.length()>0).count();
System.out.println(wordsCount);
要清点所有文件,请执行以下操作:

Long filesCount = Files.walk(Paths.get(file)).count();
System.out.println(filesCount);

new SimpleEntry(word,1)是否每次都将映射值设置为1?您可以使用Function.identity(),而无需创建SimpleEntry并使用SimpleEntry::getKey。要简化文件计数,请尝试查看文件。我想是的。这样做是不对的吗?这是不合理的。@Egorlitvineko我可以真诚地说,我的导师写了那个代码!:)这很好,但是如果你想计算一个文件目录,你不需要使用DirectoryStream吗?是的,你可以使用DirectoryStream在一个目录中迭代条目。我刚刚给你展示了另一种方法。