我想读取一个文件,并且要收集顶部n单词取决于词频。使用Java从文件中找出'n'最频繁的单词?
我试过以下代码来计算字符串中的每个单词。
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("txtFile.txt");
BufferedReader br = new BufferedReader(fr);
String text = "";
String sz = null;
while ((sz = br.readLine()) != null) {
text = text.concat(sz);
}
String[] words = text.split(" ");
String[] uniqueLabels;
int count = 0;
System.out.println(text);
uniqueLabels = getLabels(words);
for (String l: uniqueLabels) {
if ("".equals(l) || null == l) {
break;
}
for (String s: words) {
if (l.equals(s)) {
count++;
}
}
System.out.println("Word :: " + l + " Count :: " + count);
count = 0;
}
}
而且我用下面的代码,以收集独特lbels(话)得到,如果从link,
private static String[] getLabels(String[] keys) {
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for (int i = 1; i < keys.length; i++) {
for (int j = 0; j <= uniqueKeyIndex; j++) {
if (keys[i].equals(uniqueKeys[j])) {
keyAlreadyExists = true;
}
}
if (!keyAlreadyExists) {
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
而且这工作得很好,我想收集排名前十的话取决于它的文件中的频率。
能使用'Apache的集合IO HashBag'。 – ifly6
也应该切换到'List'而不是'String []'。 – ifly6
不,你不应该,因为在这种情况下循环是一个坏主意。 – Silverclaw