【发布时间】:2015-06-14 02:51:27
【问题描述】:
我正在完成一项 Comp Sci 作业。最后,程序将确定文件是用英语还是法语编写的。现在,我正在努力使用计算 .txt 文件中出现的单词频率的方法。
我在标记为 1-20 的文件夹中分别有一组英文和法文文本文件。该方法要求提供一个目录(在这种情况下是“docs/train/eng/”或“docs/train/fre/”)以及程序应该通过多少个文件(每个文件夹中有 20 个文件) .然后它读取该文件,将所有单词分开(我不需要担心大小写或标点符号),并将每个单词连同它们在文件中的次数一起放入 HashMap 中。 (键 = 词,值 = 频率)。
这是我为该方法编写的代码:
public static HashMap<String, Integer> countWords(String directory, int nFiles) {
// Declare the HashMap
HashMap<String, Integer> wordCount = new HashMap();
// this large 'for' loop will go through each file in the specified directory.
for (int k = 1; k < nFiles; k++) {
// Puts together the string that the FileReader will refer to.
String learn = directory + k + ".txt";
try {
FileReader reader = new FileReader(learn);
BufferedReader br = new BufferedReader(reader);
// The BufferedReader reads the lines
String line = br.readLine();
// Split the line into a String array to loop through
String[] words = line.split(" ");
int freq = 0;
// for loop goes through every word
for (int i = 0; i < words.length; i++) {
// Case if the HashMap already contains the key.
// If so, just increments the value
if (wordCount.containsKey(words[i])) {
wordCount.put(words[i], freq++);
}
// Otherwise, puts the word into the HashMap
else {
wordCount.put(words[i], freq++);
}
}
// Catching the file not found error
// and any other errors
}
catch (FileNotFoundException fnfe) {
System.err.println("File not found.");
}
catch (Exception e) {
System.err.print(e);
}
}
return wordCount;
}
代码编译。不幸的是,当我要求它打印 20 个文件的所有字数统计结果时,it printed this。这完全是胡言乱语(尽管这些话肯定在那里),根本不是我需要的方法。
如果有人可以帮助我调试我的代码,我将不胜感激。我已经做了很多年了,一次又一次地进行测试,我准备放弃了。
【问题讨论】:
-
你应该把你的代码分成不同的方法。例如一种方法可能是
static HashMap<String, Integer> frequency(List<String> strings) {...}
标签: java loops hashmap try-catch