程序就是數據結構+算法,要解決這個問題,我們得找到適用的數據結構以及一個好的算法。
既然要找出出現頻率最高的10個單詞,我們必須統計每個單詞出現的次數。一個單詞對應一個數字,在java中這種結構用map來實現最方便了,key-value形式的鍵值對,不會重復又可以很好的統計結果。
關於這個問題的算法,我沒有想到特別好的,就是利用一些文件操作函數,遍歷整個文本,統計單詞。
具體實現步驟:
1、遍歷文本,統計不同單詞出現的次數(這里要注意判別是否是單詞)。
2、對map的value進行降序排列(這里運用了java中collections.sort()方法來排序),列出前十個單詞。
先貼上用visualvm測試的截圖:


以下是我的代碼:
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import junit.framework.TestCase;
public class search {
public static void main(String[] args) throws FileNotFoundException
{
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();
}
Map<String,Integer> map=new TreeMap<String,Integer>();
File file=new File("test.txt");//將文本文件與代碼放入同一目錄下,所以只寫了相對路徑
Reader reader=null;
StringBuilder exist=new StringBuilder();
try
{
reader=new InputStreamReader(new FileInputStream(file));
int tmpchar;
while((tmpchar=reader.read())!=-1)
{
if(isCharacter(tmpchar))
{
exist.append((char)tmpchar);
}
else
{
Addword(exist.toString(),map);
exist=new StringBuilder();
}
}
}catch(IOException e)
{
e.printStackTrace();
}
List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
Collections.sort(list,new Comparator<Map.Entry<String,Integer>>()
{
public int compare(Entry<String,Integer> o1,Entry<String,Integer> o2)
{
return (o2.getValue().compareTo(o1.getValue()));//降序排序
}
});
int i=10;
Set<String> keySet = map.keySet();
Iterator<String> iter = keySet.iterator();
while (iter.hasNext()&&i>0)
{
String key=iter.next();
System.out.println((String)key+":"+map.get(key));
i--;
}
}
public static void Addword(String str,Map<String,Integer> map)//是字母就append組成單詞
{
str=str.toLowerCase();
Integer count=map.get(str);
if(count==null)
{
map.put(str,1);
}
else
{
map.put(str,count+1);
}
}
public static boolean isCharacter(int tmpchar)//判斷是否是字母
{
if(tmpchar>=65&&tmpchar<=90)
{
return true;
}
else if(tmpchar>=97&&tmpchar<=122)
{
return true;
}
return false;
}
}
運行結果(所選文本是一篇以a開頭的詞匯,所以結果都是a開頭的):
abolish:1
運行結果(所選文本是一篇以a開頭的詞匯,所以結果都是a開頭的):
a:37
abbr:10
abbreviation:5
ability:4
able:4
able:4
abroad:3
absence:3
absent:2
absenteeism:2 abolish:1
