java - 如何计算文本文件中的单词数,java 8-style

标签 java lambda java-8 java-stream word-count

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

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;
        }
    }

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

  }
}

该程序使用具有 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 - 如何计算文本文件中的单词数,java 8-style,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47594679/

相关文章:

c++ - 将通用 Lambda 与 std::find_if 结合使用

java - 收集器 lambda 返回可观察列表

java - Java7 和 Java8 中 switch-case 语句的行为不一致

java - 如何在Java中的抽象父类的子类中初始化 protected 最终变量?

java - 按顺序运行 Hadoop Mapper

c++ - 在 C++11 中调用 lambda 从高阶函数返回时出现段错误

java - JDK 9 的 JCE zip 文件

java - JSF 1.2、Richfaces 3.X 和 Jboss 服务器 5.0 : After Adding Richfaces JAR it's giving Error

java - 如何修复 IntelliJ 中的 'Cannot resolve AutoValue_MyClass'

java - 使用 Java 8 Optional<T>, Stream 遍历包含真实 boolean 字段值的对象列表