如何计算字符串中的单词并按降序(按其出现次数)打印包含每个单词及其出现的列表? [英] How do I count words in a string and print a list consisting of every words and their occurrences in decending order( by their occurrences)?

查看:100
本文介绍了如何计算字符串中的单词并按降序(按其出现次数)打印包含每个单词及其出现的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Solution {
  static String[][] wordCountEngine(String document) {
    Hashtable ht=new Hashtable();
    String words[]=document.split(" ");  //split sentence to words
    int largestcount=0;
    String word;
    for(int i=0;i<words.length;i++)
    { word=words[i].toLowerCase();      // ignoring case-sensitive by converting all 
                                        //  to lowercase
    List<character> li=new ArrayList<character>();
    for (char ch:word.tocharArray())
      if(ch>='a' && ch<='z')
        li.add(ch);                   //ignoring special characters like '@'and digits 
                                      //and adding it to list
    String s="";
    for(char ch:li)
      s=s+ch;                        //words without special characters and digits
    if(s.length()<1)
      continue;
    int count=0;
     
       while(document.contains(s))        //while words present in given sentence
       {    
            document=document.substring(document.indexOf(s)+s.length(),document.length()-1);
            count++;
        }
    else 
      count=1;
    if(count>largestcount)
      largestcount=count;
    //ht.put(s,count);  
  }





我的尝试:



计算单词后,我无法将其转换为由单词及其出现组成的列表,并根据出现的降序显示它们。



示例

输入:



What I have tried:

After counting the words I'm not able to convert it into a list consisting of word and its occurrences and displaying them according to their descending order of occurrences.

Example
input:

document = "Practice makes perfect. you'll only
                    get Perfect by practice. just practice!"



输出:


output:

[ ["practice", "3"], ["perfect", "2"],
          ["makes", "1"], ["youll", "1"], ["only", "1"], 
          ["get", "1"], ["by", "1"], ["just", "1"] ]

推荐答案

使用 SortedMap(Java Platform SE 8) [ ^ ]单词是关键,计数是值。如果Map不包含该单词,则将其添加,并将其值设置为1.如果地图确实包含该键,则只增加其值。
Use a SortedMap (Java Platform SE 8 )[^] with the word being the key and the count being the value. If the Map does not contain the word then add it in, and set its value to 1. If the map does contain the key then just increment its value.


这篇关于如何计算字符串中的单词并按降序(按其出现次数)打印包含每个单词及其出现的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆