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

该博客介绍了如何使用Java编程找出文本中出现频率最高的10个单词。通过遍历文本,统计每个单词的出现次数,利用HashMap存储单词及其频率,然后对频率进行降序排序,展示前十个高频单词。
摘要由CSDN通过智能技术生成

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

既然要找出出现频率最高的10个单词,我们必须统计每个单词出现的次数。一个单词对应一个数字,在java中这种结构用map来实现最方便了,key-value形式的键值对,不会重复又可以很好的统计结果。

关于这个问题的算法,我没有想到特别好的,就是利用一些文件操作函数,遍历整个文本,统计单词。

具体实现步骤:

1、遍历文本,统计不同单词出现的次数(这里要注意判别是否是单词)。

2、对map的value进行降序排列(这里运用了java中collections.sort()方法来排序),列出前十个单词。

先贴上用visualvm测试的截图:

34538f9f4e1b6d09c8c6cf5fc3acdbb5.gif

5458b40f6096a009979350fd6efdf988.gif

以下是我的代码:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值