java - 将词频添加到哈希表

标签 java hashtable

我正在尝试编写一个程序,从文件中获取单词并将它们放入哈希表中。然后我必须像这样计算单词的频率和输出:单词,出现次数。 我知道我的添加方法搞砸了,但我不知道该怎么做。我是 Java 新手。

public class Hash {

private Hashtable<String, Integer> table = new Hashtable<String, Integer>();

public void readFile() {

    File file = new File("file.txt");

    try {

        Scanner sc = new Scanner(file);

        String words;

        while (sc.hasNext()) {
            words = sc.next();
            words = words.toLowerCase();

            if (words.length() >= 2) {
                table.put(words, 1);
                add(words);
            }
        }
        sc.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

public void add(String words) {

    Set<String> keys = table.keySet();
    for (String count : keys) {
        if (table.containsKey(count)) {
            table.put(count, table.get(count) + 1);
        } else {
            table.put(count, 1);
        }
    }
}

public void show() {

    for (Entry<String, Integer> entry : table.entrySet()) {
        System.out.println(entry.getKey() + "\t" + entry.getValue());
    }
}

public static void main(String args[]) {

    Hash abc = new Hash();

    abc.readFile();

    abc.show();
}
}

这是我的文件.txt

one one
two
three
two

输出:

two , 2
one , 5
three , 3

最佳答案

Set<String> keys = table.keySet();
for (String count : keys) {
    if (table.containsKey(count)) {
        table.put(count, table.get(count) + 1);
    } else {
        table.put(count, 1);
    }
}

现在,您正在递增 map 中已有的键。相反,我不认为你想遍历任何东西,你只想为 words 增加 if 条件,我认为它实际上只代表一个词。

if (table.containsKey(words)) {
   table.put(words, table.get(words) + 1);
} else {
   table.put(words, 1);
}

关于java - 将词频添加到哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30084511/

相关文章:

Java XSD : validate only by mandatory

c++ - std::hash 对于不同编译版本和不同机器的相同输入是否给出相同的结果?

java - Java中广泛使用的哈希算法用于实现哈希表?

java - HashMap 难点

java - 在这种高流量的多线程场景中,我应该使用 ThreadLocal 吗?

java - 如何正确测试这种定时并发处理服务呢?

java - 如何编写实用程序类以便我可以使用 DTO 设计模式执行延迟加载?

java - firebase-api-initialization-failure-java-lang-reflect-invocationtargetexception

c - 两个哈希表,双键哈希表还是不同的解决方案?

java - 寻找有效的方法将哈希表的元素提取到单个数组中