【发布时间】:2012-02-14 04:33:16
【问题描述】:
我一直在阅读地图并了解树形地图和散列、排序地图的一些差异。我试图在输出地图时对其进行排序。
我需要做的是:
- 获取一个文本文件并读入内容。
- 将其分成单独的单词。使用单词作为键,使用值作为
key在 txt 文件中出现的次数。 - 如果单词位于句尾,我将使其成为单独的键。例如,
my和my.是两个独立的键。
我的问题是,无论我将它声明为树、散列还是排序映射,我都无法让它以有序的方式输出/迭代。我希望它首先以最高出现的值输出,但我什至无法让它以任何顺序与键一起输出。
public static Map<String, Integer> createDictionary(String _filename)
{
TreeMap<String, Integer> dictionary = new TreeMap<String, Integer>(); // Changed Hash to _______
try {
FileReader myFileReader=new FileReader(_filename); // File reader stream open
BufferedReader myBuffReader=new BufferedReader(myFileReader);
String str = "\0";
while (str != null) { // While there are still strings in the file
str = myBuffReader.readLine(); // We read a line into the str variable
if (str != null) { // Make sure its not the last line/EOF
// System.out.println(str); // Used for testing.
StringTokenizer myTokenStr=new StringTokenizer(str," \t"); // Create a StringToken obj from the string
while (myTokenStr.hasMoreTokens()) {
String tokStr = myTokenStr.nextToken(); // Each token is put into an individual string
// System.out.println(tokStr);
if (dictionary.containsKey(tokStr)) {
int value = dictionary.get(tokStr); // Add one to the integer value
// dictionary.remove(tokStr); // Was doing this way but just using put method works
// dictionary.put(tokStr, value + 1);
dictionary.put(tokStr, value + 1);
}
else {
dictionary.put(tokStr, 1); // Add the string as the key with an int value of one for the value
}
}
}
}
myBuffReader.close(); // Close stream
myFileReader.close(); // Close stream
}
catch (FileNotFoundException e) {
System.out.println("File Not Found");
}
catch (IOException e) { }
// System.out.println(dictionary.entrySet());
return dictionary;
}
【问题讨论】:
-
首先,您确定要在
" \t"上进行标记吗?当您说“分解成单词”时,默认标记字符串在一般情况下似乎更匹配,即StringTokenizer(str)您不会以标记化的方式匹配换行符。你到底是如何迭代的? (另外,如果你想对它进行排序,忘记 HashMap,TreeMap 是唯一的方法) -
Stiles... 它以正确的字数输出正确的单词,但这些单词不是按字母顺序排列的,或者值/字数是按顺序排列的。它像哈希图一样随机。 Irfy .... "\t" 上的标记应该在空格和制表符上标记。唯一的另一个是行尾,并且已经处理好了。我可能错了,但它与 c++ tokinize 类似,并且它适用于我发送的测试用例。