Как найти в тексте наиболее часто встречающееся слово? - PullRequest
0 голосов
/ 28 мая 2020

У меня проблема. Похоже, если у меня есть ввод вроде этого: «Спасибо, спасибо, спасибо, автомобиль». Результат будет «спасибо». Если мое слово начинается с заглавной буквы, оно напечатает это слово со строчной буквы. Что я могу добавить к своему решению, чтобы решить эту проблему?

 public class Main {
 public static void main(String[] args) throws IOException {
     String line;
     String[] words = new String[100];
     Map < String, Integer > frequency = new HashMap < > ();
     BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
     while ((line = reader.readLine()) != null) {
         line = line.trim();
         if (!line.isEmpty()) {
             words = line.split("\\W+");
             for (String word: words) {
                 String processed = word.toLowerCase();
                 processed = processed.replace(",", "");

                 if (frequency.containsKey(processed)) {
                     frequency.put(processed,
                         frequency.get(processed) + 1);
                 } else {
                     frequency.put(processed, 1);
                 }
             }
         }
     }
     int mostFrequentlyUsed = 0;
     String theWord = null;

     for (String word: frequency.keySet()) {
         Integer theVal = frequency.get(word);
         if (theVal > mostFrequentlyUsed) {
             mostFrequentlyUsed = theVal;
             theWord = word;
         } else if (theVal == mostFrequentlyUsed && word.length() <
             theWord.length()) {
             theWord = word;
             mostFrequentlyUsed = theVal;
         }

     }
     System.out.printf(theWord);
 }

Ответы [ 2 ]

1 голос
/ 28 мая 2020

Чтобы код печатал наиболее часто встречающееся слово в том формате, в котором он был введен, а не в нижнем регистре, вы можете изменить строку кода ниже.

String processed = word.toLowerCase();

Измените его на:

String processed = word;

Но тогда имейте в виду, что метод containsKey() учитывает регистр и не будет рассматривать «Спасибо» и «спасибо» как одно и то же слово.

0 голосов
/ 28 мая 2020
Please find the below program which print both upper and lower case based on input.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

 public class Main {
 public static void main(String[] args) throws IOException {

     BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
     String[] strArr=reader.readLine().split(" ");
     String result=null;
     int maxCount=0;
     Map<String, Integer> strMap=new HashMap<String, Integer>();
     int count=0;
     for(String s:strArr){
         count=0;
         if(strMap.containsKey(s)){
             count=strMap.get(s);
             strMap.put(s,++count);
         }else{
             strMap.put(s, ++count);
         }
     }  
         //find Maximum

         for(Map.Entry<String, Integer> itr: strMap.entrySet()){

             if(maxCount==0){                
                 maxCount=itr.getValue();
                 result=itr.getKey();                
             }else{

                 if(maxCount < itr.getValue()){                  
                     maxCount=itr.getValue();
                     result=itr.getKey();
                 }
             }   
         }

         // No of occurences with count
         System.out.println("word"+ result+"count"+ maxCount);

         printInLowerOrUpperCare(result);

 }

      public static void printInLowerOrUpperCare(String result){

          if(result.charAt(0) >='a' && result.charAt(0) >= 'z' ){

              System.out.println(result.toUpperCase());
          }else{
              System.out.println(result.toLowerCase());
          }           

      }

 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...