Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 计算与字符串[]中的单词匹配的文件中的单词数_Java_Arrays_String_File - Fatal编程技术网

Java 计算与字符串[]中的单词匹配的文件中的单词数

Java 计算与字符串[]中的单词匹配的文件中的单词数,java,arrays,string,file,Java,Arrays,String,File,我正在编写一个程序来读取一个文件,并计算该文件中特定单词的出现次数 我已经让代码工作到一定程度。我把我想数数的单词放在一个字符串[]。问题是程序要么统计文件中所有单词的出现次数(包括我不想统计的单词),要么统计字符串[]中的单词 如何让程序计算文件中与数组中的字匹配的字?我已经研究了许多类似的问题,并尝试使用StringTokenizer和List,但也无法让它们完全工作 我的目标是,如果我的文件有文本“黄-红-蓝-白-黑-紫-蓝”,我希望我的输出是“红:1,蓝:2,黄:1” 我只想在正确的方向

我正在编写一个程序来读取一个文件,并计算该文件中特定单词的出现次数

我已经让代码工作到一定程度。我把我想数数的单词放在一个字符串[]。问题是程序要么统计文件中所有单词的出现次数(包括我不想统计的单词),要么统计字符串[]中的单词

如何让程序计算文件中与数组中的字匹配的字?我已经研究了许多类似的问题,并尝试使用StringTokenizer和List,但也无法让它们完全工作

我的目标是,如果我的文件有文本“黄-红-蓝-白-黑-紫-蓝”,我希望我的输出是“红:1,蓝:2,黄:1”

我只想在正确的方向上推动一下,我知道这是一件愚蠢的事情,我一直坚持下去,和往常一样,任何建设性的反馈都是非常感谢的

以下是我目前的代码:

static String[] words = { "red", "blue", "yellow", "green" };

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

    System.out.println("This program will count the occurences of the specific words from a text file.");

    System.out.println("\nThe words to be counted are; red, blue, yellow, and green.\n");

    Map map = new HashMap();

    try (BufferedReader br = new BufferedReader(new FileReader("colours.txt"))) {

        StringBuilder sb = new StringBuilder();

        String line = br.readLine();

        while (line != null) {

            words = line.split(" "); // keeping this counts all words separated by whitespace, removing it counts words in my array instead of the file, so I'll get red: 1, blue: 1, yellow: 1 etc.,

            for (int i = 0; i < words.length; i++) {

                if (map.get(words[i]) == null) {

                    map.put(words[i], 1);
                }

                else {

                    int newValue = Integer.valueOf(String.valueOf(map.get(words[i])));

                    newValue++;

                    map.put(words[i], newValue);
                }

            }

            sb.append(System.lineSeparator());

            line = br.readLine();
        }
    }

    Map<String, String> sorted = new TreeMap<String, String>(map);

    for (Object key : sorted.keySet()) {

        System.out.println(key + ": " + map.get(key));
    }
}
static String[]words={“红色”、“蓝色”、“黄色”、“绿色”};
公共静态void main(字符串[]args)抛出FileNotFoundException、IOException{
System.out.println(“此程序将统计文本文件中特定单词的出现次数。”);
System.out.println(“\n要计数的字是:红色、蓝色、黄色和绿色。\n”);
Map Map=newhashmap();
try(BufferedReader br=newbufferedreader(newfilereader(“colors.txt”)){
StringBuilder sb=新的StringBuilder();
String line=br.readLine();
while(行!=null){
words=line.split(“”;//保留此选项将统计所有以空格分隔的单词,删除此选项将统计数组中的单词,而不是文件中的单词,因此我将得到红色:1、蓝色:1、黄色:1等。,
for(int i=0;i
上面的主要问题是,当您拆分刚刚读取的行时,您正在覆盖初始数组或
单词

我已经写了这篇文章(为了我自己的理解修改了一些变量名)

根据评论更新,谢谢@shmosel)

publicstaticvoidmain(字符串[]args)抛出FileNotFoundException、IOException{
字符串[]关键字={“红色”、“蓝色”、“黄色”、“绿色”};
//为了更方便地查询数组的内容
List关键字List=Arrays.asList(关键字);
System.out.println(“此程序将统计文本文件中特定单词的出现次数。”);
System.out.println(“\n要计数的字是:“+keywordList+”);
Map wordMap=newhashmap();
try(BufferedReader br=new BufferedReader(new FileReader(“/path/to/file/colors.txt”)){
//读一行
String line=br.readLine();
while(行!=null){
//保留此值将计算所有用空格分隔的单词,删除此值将计算数组中的单词
//所以我会得到红色:1,蓝色:1,黄色:1等等。,
String[]words=line.split(“”);
for(字符串一个字:字){
if(关键字列表.包含(一个单词)){
//感谢@shmosel在评论中提出的改进建议
merge(一个字,1,整数::和);
}
}
line=br.readLine();
}
}
映射排序=新树映射(wordMap);
for(对象键:sorted.keySet()){
System.out.println(key+”:“+wordMap.get(key));
}
}

代码中可能有两个问题

  • 数组“words”最初用于列出您感兴趣的单词。 但是您使用的是相同的数组来保存行中的单词。 [请参见words=line.split(“”;),因此请使用不同的数组来保存行中的单词
  • 没有检查单词(在初始列表中)是否存在于 线路。需要添加此支票。另外,记住一个单词可以在同一行中重复多次

Files.lines(path.get(“colors.txt”)).flatMap(Pattern.compile(“”)::splitAsStream)。filter(新哈希集(Arrays.asList(words))::contains)。collect(Collectors.groupingBy(Function.identity(),Collectors.counting()).forEach((k,v)->System.out.println(k+“:“+v))@ochi,这就是为什么我没有将其作为答案发布。@shmosel你应该这样做!!!它给人留下了深刻的印象(哦,它确实有效!!!刚刚尝试过;)@shmosel我可以理解它是如何工作的,但我还不知道如何在我的代码中实现它。我将尝试:)这就是全部代码。把你的
main()
放进去,你就设置好了。
wordMap.merge(oneWord,1,Integer::sum)是的,我现在看到它,当它被指给我时,需要另一个数组来存放我文件中的单词。感谢您花时间向我展示如何实现代码,非常感谢。我现在要试着弄清楚它是如何工作的以及为什么工作的:)啊,这样一个新手的错误:)谢谢你的反馈,一旦我让代码工作起来,我会尝试合并一个检查。
public static void main(String[] args) throws FileNotFoundException, IOException {

    String[] keywords = {"red", "blue", "yellow", "green"};
    // for easier querying contents of array
    List keywordList = Arrays.asList(keywords);

    System.out.println("This program will count the occurrences of the specific words from a text file.");
    System.out.println("\nThe words to be counted are: " + keywordList + ".\n");

    Map<String, Integer> wordMap = new HashMap<>();

    try (BufferedReader br = new BufferedReader(new FileReader("/path/to/file/colours.txt"))) {
        // read a line
        String line = br.readLine();

        while (line != null) {
            // keeping this counts all words separated by whitespace, removing it counts words in my array instead
            // of the file, so I'll get red: 1, blue: 1, yellow: 1 etc.,
            String[] words = line.split(" ");

            for(String oneWord : words ){
                if( keywordList.contains(oneWord)){
                    // thanks @ shmosel for the improvement suggested in comments
                    wordMap.merge(oneWord, 1, Integer::sum);
                }
            }

            line = br.readLine();
        }
    }

    Map<String, Integer> sorted = new TreeMap<>(wordMap);

    for (Object key : sorted.keySet()) {
        System.out.println(key + ": " + wordMap.get(key));
    }
}