【求解】英文文本中提取其中的单词,从高到低显示单词的使用频率排序,大小写不限

 编写一个程序,处理一个自己建立的英文文本(类似网上的帖子),提取其中的单词,从高到低显示单词的使用频率排序,大小写不限。排序算法不限。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;

import javax.swing.JOptionPane;

public class CharacterCount {
 public static void main(String[] args) {
  //获取输入文字列
  String input = JOptionPane.showInputDialog("Please input character!");
  
  while (null == input || "".equals(input.trim())) {
   JOptionPane.showMessageDialog(null, "Please input character!");
   input = JOptionPane.showInputDialog("Please input character!");
  }
  //取出单词
  String[] ary = input.split("\\s+");
  
  List<String> list = new ArrayList<String>();
  for ( String str : ary ) {
   //取出的单词数组中提出标点符号
   if ( !str.matches("\\W+") ) {
    list.add(str);
   }
  }
  //创建集合对象,将链表存入集合对象,自动删除重复单词,此时集合的size就是剔除重复后的单词个数
  Set<String> set = new HashSet<String>(list);
  //创建映射对象,以单词出现次数为key,单词内容为value存储
  Map<Integer, String> map = new HashMap<Integer, String>();
  for ( String str : set ) {
   int count = 0;
   while (true) {
    int index = list.indexOf(str);
    if ( index >= 0 ) {
     count++;
     list.remove(index);
    } else {
     break;
    }
   }
   //key在map中已经存在时用空格将单词分隔
   if ( null == map.get(new Integer(count)) ) {
    map.put(new Integer(count), str);
   } else {
    String value = map.get(new Integer(count));
    map.put(new Integer(count), str + " " + value);
   }
  }
  //按照出现次数升序
  sort(map,true);
  //按照出现次数降序
  sort(map,false);
 }
 
 /**
  * 排序用方法.
  * @param map 待排序容器对象
  * @param sortType 排序种别,true表示升序,false表示降序
  */
 public static void sort( Map<Integer, String> map, boolean sortType ) {
  List<String> list = new ArrayList<String>();
  //创建优先队列用于排序
  Queue<Integer> queue = new PriorityQueue<Integer>(map.keySet());
  
  String[] ary;
  while ( queue.size() != 0 ) {
   Integer integer = queue.poll();
   if ( !sortType ) {
    ary = map.get(integer).split(" ");
    for ( String str : ary ) {
     list.add(0, str + "有" + integer + " 个" );
    }
   } else {
    ary = map.get(integer).split(" ");
    for ( String str : ary ) {
     list.add(str + "有" + integer + " 个");
    }
   }
  }
  System.out.println(list);
  
 }
}
以上程序转自http://zhidao.baidu.com/question/189849795.html?fr=qrl&cid=93&index=3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值