程序就是数据结构+算法,要解决这个问题,我们得找到适用的数据结构以及一个好的算法。
既然要找出出现频率最高的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