将单词频率添加到哈希表中。
将单词频率添加到哈希表中。
我正在尝试编写一个程序,从文件中获取单词并将它们放入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 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(); } }
这是我的file.txt文件
one one two three two
输出:
two , 2 one , 5 three , 3
admin 更改状态以发布 2023年5月21日
你可以将add函数去掉。你在将值设为1后尝试递增。相反,我会这样编写:
try (Scanner sc = new Scanner(file)) { while (sc.hasNext()) { String word = sc.next().toLowerCase(); if (words.length() >= 2) { Integer count = table.get(word); table.put(word, count == null ? 1 : (count+1)); } } }
注意:在Java 8中,您可以在一行中完成所有这些操作,同时并行处理每个行。
MapwordCount = Files.lines(path).parallel() .flatMap(line -> Arrays.asList(line.split("\\b")).stream()) .collect(groupingByConcurrent(w -> w, counting()));
Setkeys = table.keySet(); for (String count : keys) { if (table.containsKey(count)) { table.put(count, table.get(count) + 1); } else { table.put(count, 1); } }
目前,您正在增加地图中已有的键。相反,我认为您不想循环遍历任何内容,而只想为words
设置if
条件增量,实际上我认为words
仅表示一个单词。
if (table.containsKey(words)) { table.put(words, table.get(words) + 1); } else { table.put(words, 1); }