1. 程式人生 > >使用StringTokenizer分割並統計單詞個數

使用StringTokenizer分割並統計單詞個數

在某些時候,可能會需要統計一大串文字中出現的單詞個數。一般情況下,直接想到的是用正則表示式,但是我偶然發現了一個比用正則表示式更好的方法。

也就是使用StringTokenizer這個類,參考文件:

傳入指定字元如逗號、冒號等作為分割標誌,取出單詞。

public static HashMap<String, Integer> getWordCount(StringBuffer contents) {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		StringTokenizer tokenizer = new StringTokenizer(new String(contents));
		int count;
		String word;
		while (tokenizer.hasMoreTokens()) {
			word = tokenizer.nextToken(" ,?.!:\"\"''\n");
			if (map.containsKey(word)) {
				count = map.get(word);
				map.put(word, count + 1);
			} else {
				map.put(word, 1);
			}
		}
		return map;
	}
將取出的單詞以及它出現的頻率儲存至HashMap中,然後根據頻率大小從大至小排序。
public static ArrayList<Entry<String, Integer>> sortWordCount(
			HashMap<String, Integer> map) {
		ArrayList<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(
				map.entrySet());
		Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
			public int compare(Map.Entry<String, Integer> o1,
					Map.Entry<String, Integer> o2) {
				return (o2.getValue() - o1.getValue());
			}
		});
		return infoIds;
	}

最後在main函式中呼叫函式進行單詞個數統計並輸出結果。(資料來源採用txt格式的英文小說,大小為300KB)


為了能夠使用VisualVM測試其效能,需要在呼叫統計的程式碼前呼叫如下程式碼。

System.out.println("Press any letter to start word count:");
		Scanner s = new Scanner(System.in);
		if (s.nextLine() == null) {
			s.close();
			System.exit(0);
		} else {
			s.close();
		}
最後,獲得的效能分析結果如下圖。