gpt4 book ai didi

java - 使用 Stream stream = Arrays.stream(words) 过滤唯一字数;

转载 作者:行者123 更新时间:2023-11-29 04:35:08 27 4
gpt4 key购买 nike

我正在尝试创建一个单一的衬里,它应该计算一个非常长的文本文件中的唯一单词。独特的词例如:márya fëdorovna scarlet-liveried,...所以基本上都是非英语词。

我的问题是我的代码过滤的单词不够多。我的代码:

    String text = readText("longlongtextfile"); // My own method for readText
String[] words = text.split(" ");

System.out.println("Initial word count: " + words.length);

Stream <String> stream = Arrays.stream(words);
long uniqueWords = stream.map(String::toLowerCase).distinct().count();

System.out.println(uniqueWords);

我想应用 .filter(i -> i >= 'a' && i <= 'z').distinct().count() 但这对字符串流不起作用。

所以我的问题是,如果字符串流有类似的 a-Z 过滤器

最佳答案

要计算包含 a-z 以外字符的单词,您可以使用正则表达式进行过滤:

Arrays.stream(tokens).map(String::toLowerCase).filter(t -> !t.matches("[a-z]+")).distinct().count();

要找到唯一标记的数量,您需要计算它们出现的次数:

long uniqueWordCount = Arrays.stream(tokens)
.map(String::toLowerCase)
// Build a map from word -> frequency
.collect(Collectors.groupingBy(w -> w, Collectors.counting()))
// stream the frequency map entries
.entrySet().stream()
// filter to retain unique words (with frequency == 1)
.filter(e -> e.getValue() == 1)
// count them
.count();

关于java - 使用 Stream <String> stream = Arrays.stream(words) 过滤唯一字数;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41926239/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com