繁体   English   中英

检查文件中单词列表的最有效方法

[英]Most Efficient Way to Check File for List of Words

我刚完成一项作业,希望我将所有Java关键字添加到HashSet中。 然后读入一个.java文件,并计算任何关键字出现在.java文件中的次数。

我采取的方法是:创建一个包含所有关键字的String []数组。 创建一个HashSet,并使用Collections.addAll将数组添加到HashSet中。 然后,当我遍历文本文件时,将通过HashSet.contains(currentWordFromFile);对其进行检查。

有人建议使用HashTable执行此操作。 然后我看到了一个使用TreeSet的类似示例。 我只是好奇..推荐这样做的方法是什么?

(在此处完成代码: http : //pastebin.com/GdDmCWj0

尝试使用Map<String, Integer> ,其中String是单词,而Integer是出现该单词的次数。

这样的好处之一是您不需要处理文件两次。

您说“有家庭作业”,所以我假设您已经完成了。

我会做一些不同的事情。 首先,我认为您的String数组中的某些关键字不正确。 根据WikipediaOracle的说法,Java有50个关键字。 无论如何,我已经很好地注释了我的代码。 这是我想出的...

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

public class CountKeywords {

    public static void main(String args[]) {

        String[] theKeywords = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" };

        // put each keyword in the map with value 0 
        Map<String, Integer> theKeywordCount = new HashMap<String, Integer>();
        for (String str : theKeywords) {
            theKeywordCount.put(str, 0);
        }

        FileReader fr;
        BufferedReader br;
        File file = new File(args[0]);

        // attempt to open and read file
        try {
            fr = new FileReader(file);
            br = new BufferedReader(fr);

            String sLine;

            // read lines until reaching the end of the file
            while ((sLine = br.readLine()) != null) {

                // if an empty line was read
                if (sLine.length() != 0) {

                    // extract the words from the current line in the file
                    if (theKeywordCount.containsKey(sLine)) {
                        theKeywordCount.put(sLine, theKeywordCount.get(sLine) + 1);
                    }
                }
            }

        } catch (FileNotFoundException exception) {
            // Unable to find file.
            exception.printStackTrace();
        } catch (IOException exception) {
            // Unable to read line.
            exception.printStackTrace();
        } finally {
                br.close();
            }

        // count how many times each keyword was encontered
        int occurrences = 0;
        for (Integer i : theKeywordCount.values()) {
            occurrences += i;
        }

        System.out.println("\n\nTotal occurences in file: " + occurrences);
    }
}

每次遇到文件中的关键字时,我都会先检查它是否在Map中; 如果不是,则它不是有效的关键字; 如果是,那么我将更新与关键字关联的值,即,将关联的Integer递增1,因为我们再次看到了此关键字。

或者,您可以摆脱最后一个for循环,而只需保持运行计数,那么您将拥有...

if (theKeywordCount.containsKey(sLine)) {
    occurrences++;
}

...,然后在最后打印出计数器。

我不知道这是否是最有效的方法,但我认为这是一个坚实的开端。

如果您有任何疑问,请告诉我。 我希望这有帮助。
斯托伊奇

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM