使用StringTokenizer分割并统计单词个数

在某些时候,可能会需要统计一大串文本中出现的单词个数。一般情况下,直接想到的是用正则表达式,但是我偶然发现了一个比用正则表达式更好的方法。

也就是使用StringTokenizer这个类,参考文档:

http://developer.android.com/reference/java/util/StringTokenizer.html

传入指定字符如逗号、冒号等作为分割标志,取出单词。

public static HashMap getWordCount(StringBuffer contents) {
		HashMap map = new HashMap();
		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> sortWordCount(
			HashMap map) {
		ArrayList> infoIds = new ArrayList>(
				map.entrySet());
		Collections.sort(infoIds, new Comparator>() {
			public int compare(Map.Entry o1,
					Map.Entry o2) {
				return (o2.getValue() - o1.getValue());
			}
		});
		return infoIds;
	}

最后在main函数中调用函数进行单词个数统计并输出结果。(数据源采用txt格式的英文小说,大小为300KB)

使用StringTokenizer分割并统计单词个数_第1张图片

为了能够使用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();
		}
最后,获得的性能分析结果如下图。

使用StringTokenizer分割并统计单词个数_第2张图片


使用StringTokenizer分割并统计单词个数_第3张图片

你可能感兴趣的:(Java)