我正在做一项计算机科学作业。最后,程序将确定文件是用英语还是法语编写的。现在,我正在努力研究计算 .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 个文件的所有字数统计结果时,它打印了这个。这完全是胡言乱语(尽管这些词肯定在那里),而且根本不是我需要该方法执行的操作。
如果有人可以帮助我调试我的代码,我将不胜感激。我已经这样做了很多年,进行了一次又一次的测试,我准备放弃。
让我在这里结合所有好的答案。
1)分解你的方法,每个方法处理一件事。一个用于将文件读入字符串[],一个用于处理字符串[],一个用于调用前两个。
2)当你分手时,深入思考你想如何分手。正如 @m0skit0 建议的那样,对于这个问题,您可能应该与 \b 分开。
3)正如@jas建议的,你应该首先检查你的地图是否已经有这个词。如果它确实增加了计数,如果没有,则将单词添加到映射中并将其计数设置为 1。
4) 要按照您可能期望的方式打印地图,请查看以下内容:
Map test = new HashMap();
for (Map.Entry entry : test.entrySet()){
System.out.println(entry.getKey() + " " + entry.getValue());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)