600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > java从文本中选出单词_找出文本中出现频率最高的10个单词(java实现)

java从文本中选出单词_找出文本中出现频率最高的10个单词(java实现)

时间:2023-09-04 21:42:43

相关推荐

java从文本中选出单词_找出文本中出现频率最高的10个单词(java实现)

程序就是数据结构+算法,要解决这个问题,我们得找到适用的数据结构以及一个好的算法。

既然要找出出现频率最高的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 map=new TreeMap();

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> list = new ArrayList>(map.entrySet());

Collections.sort(list,new Comparator>()

{

public int compare(Entry o1,Entry o2)

{

return (o2.getValue().compareTo(o1.getValue()));//降序排序

}

});

int i=10;

Set keySet = map.keySet();

Iterator 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 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开头的):

a:37

abbr:10

abbreviation:5

ability:4

able:4

abroad:3

absence:3

absent:2

absenteeism:2

abolish:1

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。