使用java查找句子中任何给定单词出现的频率

时间:2017-12-20 02:48:55

标签: java

我试图使用java在句子中找到给定单词的出现。

我的输入包含两行,第一行包含一个单词,第二行包含句子。

Sample Input:
love
There is only one happiness in this life,to love and be loved.

Sample Output:
1

我在下面的程序中尝试打印值1 - 但是它打印每个单词而不是相同的单词。有人可以帮我解决这个问题吗?

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class Test {

    public static void main(String args[]) throws IOException {

        String test = "love\n" + "There is only one happiness in this life,to love and be loved.";

        System.out.println(test);

        Map<String, Integer> wordCount = Arrays.stream(test.split("\\s+"))
                .collect(Collectors.toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2));

        // Print word frequencies
        wordCount.forEach((k, v) -> System.out.printf("%s %d\n", k, v));

    }

}                       

2 个答案:

答案 0 :(得分:0)

这可以通过简单的if语句修复。您所要做的就是确保当前键与第一行匹配。为此,在映射字符串之前先获取第一行。

java

答案 1 :(得分:0)

我认为第一个问题是将键值输入计数。单独尝试:

library(feather)

dat <- data.frame(a = 1:3, b = 4:6)

write_feather(dat,  "df.feather", "I am the very model of a modern major general")

str(feather_metadata("df.feather"))
##List of 5
## $ path       : chr "df.feather"
## $ dim        : int [1:2] 3 2
## $ types      : Named chr [1:2] "integer" "integer"
##  ..- attr(*, "names")= chr [1:2] "a" "b"
## $ description: chr "I am the very model of a modern major general"
## $ version    : int 2
##  - attr(*, "class")= chr "feather_metadata"

然后

String key = "love";
String test = "There is only one happiness in this life,to love and be loved.";