weixin_39741250 2019-10-13 08:18 采纳率: 0%
浏览 194
已结题

在该限制下,如何使用最短代码的java实现相同功能

#!/usr/bin/env python
import re, sys, collections

stops = open(’../stop_words.txt’).read().split(’,’)

words = re.findall(’[a-z]{2,}’, open(sys.argv[1]).read().lower())

counts = collections.Counter(w for w in words if w not in stops)

for (w, c) in counts.most_common(25):

print w, ’-’, c

  • 写回答

1条回答 默认 最新

  • threenewbee 2019-10-13 09:32
    关注

    条件限制,我这里没法测试读取文件的部分,https://www.jianshu.com/p/72d37777c417 自己参考完善下,之后的程序已经帮你改写

    import java.util.HashMap;
    import java.util.regex.*;
    import java.util.Map;
    import java.util.*;
    
    class HelloWorld {
        public static void main(String []args) {
            String s = "someone says: hello world! hello, this website hello the people this is the java language.";
            Pattern pattern = Pattern.compile("[a-z]{2,}");
            Matcher matcher = pattern.matcher(s);
            Map<String, Integer> map = new HashMap<>();
            while (matcher.find()) {
                String word = matcher.group(0).toLowerCase();
                if(!map.containsKey(word))
                {
                    map.put(word, 1);
                }
                else
                {
                    int times = map.get(word) + 1;
                    map.remove(word);
                    map.put(word, times);
                }
            }
    
            //System.out.println(map);
            List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
            list.sort(new Comparator<Map.Entry<String, Integer>>() {
              @Override
              public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                  return o2.getValue().compareTo(o1.getValue());
              }
          });
            for (Map.Entry<String, Integer> mapping : list){
                System.out.println(mapping.getKey()+" - "+mapping.getValue());
            }    
        }
    }
    

    hello - 3
    the - 2
    this - 2
    website - 1
    world - 1
    java - 1
    someone - 1
    is - 1
    language - 1
    says - 1
    people - 1

    评论

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元