Calculating frequency of each word in a sentence in java

前端 未结 19 1969
夕颜
夕颜 2020-11-29 10:15

I am writing a very basic java program that calculates frequency of each word in a sentence so far i managed to do this much

import java.io.*;

class Linked         


        
相关标签:
19条回答
  • 2020-11-29 10:58

    Determine the frequency of words in a file.

    File f = new File(fileName);
    Scanner s = new Scanner(f);
    Map<String, Integer> counts =
     new Map<String, Integer>(); 
    while( s.hasNext() ){
     String word = s.next();
    if( !counts.containsKey( word ) )
     counts.put( word, 1 );
    else
     counts.put( word, 
      counts.get(word) + 1 );
    

    }

    0 讨论(0)
  • 2020-11-29 11:01

    You could try this

    public static void frequency(String s) {
        String trimmed = s.trim().replaceAll(" +", " ");
        String[] a = trimmed.split(" ");
        ArrayList<Integer> p = new ArrayList<>();
        for (int i = 0; i < a.length; i++) {
            if (p.contains(i)) {
                continue;
            }
            int d = 1;
            for (int j = i+1; j < a.length; j++) {
                if (a[i].equals(a[j])) {
                    d += 1;
                    p.add(j);
                }
            }
            System.out.println("Count of "+a[i]+" is:"+d);
        }
    }
    
    0 讨论(0)
  • 2020-11-29 11:01

    Count frequency of elements of list in java 8

    List<Integer> list = new ArrayList<Integer>();
    Collections.addAll(list,3,6,3,8,4,9,3,6,9,4,8,3,7,2);
    Map<Integer, Long> frequencyMap = list.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
    
        System.out.println(frequencyMap);
    

    Note : For String frequency counting split the string and convert it to list and use streams for count frequency => (Map frequencyMap)*

    Check below link

    0 讨论(0)
  • 2020-11-29 11:04

    Please try these it may be help for you

        public static void main(String[] args) {
            String str1="I am indian , I am proud to be indian proud.";
            Map<String,Integer> map=findFrquenciesInString(str1);
            System.out.println(map);
        }
    
        private static Map<String,Integer> findFrquenciesInString(String str1) {
            String[] strArr=str1.split(" ");
            Map<String,Integer> map=new HashMap<>();
            for(int i=0;i<strArr.length;i++) {
                int count=1;
                for(int j=i+1;j<strArr.length;j++) {
                    if(strArr[i].equals(strArr[j]) && strArr[i]!="-1") {
                        strArr[j]="-1";
                        count++;
                    }
                }
                if(count>1 && strArr[i]!="-1") {
                    map.put(strArr[i], count);
                    strArr[i]="-1";
                }
            }
            return map;
        }
    
    0 讨论(0)
  • 2020-11-29 11:04
    public class WordFrequencyProblem {
    
        public static void main(String args[]){
            String s="the quick brown fox jumps fox fox over the lazy dog brown";
            String alreadyProcessedWords="";
            boolean isCount=false;
            String[] splitWord = s.split("\\s|\\.");
            for(int i=0;i<splitWord.length;i++){
                String word = splitWord[i];
                int count = 0;
                isCount=false;
                if(!alreadyProcessedWords.contains(word)){
                    for(int j=0;j<splitWord.length;j++){
                            if(word.equals(splitWord[j])){
                                count++;
                                isCount = true;
                                alreadyProcessedWords=alreadyProcessedWords+word+" ";
                            }
                        }
                }
                if(isCount)
                System.out.println(word +"Present "+ count);
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-11-29 11:06

    Created a simple easy to understand solution for this problem covers all test cases-

    import java.util.HashMap;
    import java.util.Map;
    
    /*
     * Problem Statement - Count Frequency of each word in a given string, ignoring special characters and space 
     * Input 1 - "To be or Not to be"
     * Output 1 - to(2 times), be(2 times), or(1 time), not(1 time)
     * 
     * Input 2 -"Star 123 ### 123 star"
     * Output - Star(2 times), 123(2 times)
     */
    
    public class FrequencyofWords {
    
        public static void main(String[] args) {
            String s1="To be or not **** to be! is all i ask for";
            fnFrequencyofWords(s1);
            
        }
        
        //-------Supporting Function-----------------
        static void fnFrequencyofWords(String s1) {
            //------- Convert String to proper format----
            s1=s1.replaceAll("[^A-Za-z0-9\\s]","");
            s1=s1.replaceAll(" +"," ");
            s1=s1.toLowerCase();
            
            //-------Create String to an array with words------
            String[] s2=s1.split(" ");
            System.out.println(s1);
                
            //-------- Create a HashMap to store each word and its count--
            Map <String , Integer> map=new HashMap<String, Integer>();
            for(int i=0;i<s2.length;i++) {
            
            if(map.containsKey(s2[i])) //---- Verify if Word Already Exits---
                {
                    map.put(s2[i], 1+ map.get(s2[i])); //-- Increment value by 1 if word already exits--
                }
                else {
                    map.put(s2[i], 1); // --- Add Word to map and set value as 1 if it does not exist in map--
                }
            }
            System.out.println(map); //--- Print the HashMap with Key, Value Pair-------
        }
    }
    
    0 讨论(0)
提交回复
热议问题