【问题标题】:Calculating frequency of each word in a sentence in java在java中计算句子中每个单词的频率
【发布时间】:2014-03-13 08:29:54
【问题描述】:

我正在编写一个非常基本的 java 程序来计算句子中每个单词的频率到目前为止我设法做到了这一点

import java.io.*;

class Linked {

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

        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));
        System.out.println("Enter the sentence");
        String st = br.readLine();
        st = st + " ";
        int a = lengthx(st);
        String arr[] = new String[a];
        int p = 0;
        int c = 0;

        for (int j = 0; j < st.length(); j++) {
            if (st.charAt(j) == ' ') {
                arr[p++] = st.substring(c,j);
                c = j + 1;
            }
        }
    }

    static int lengthx(String a) {
        int p = 0;
        for (int j = 0; j < a.length(); j++) {
            if (a.charAt(j) == ' ') {
                p++;
            }
        }
        return p;
    }
}

我已经提取了每个字符串并将其存储在一个数组中,现在的问题实际上是如何计算每个“单词”重复的实例数以及如何显示以使重复的单词不会多次显示,你能帮忙吗我在这个?

【问题讨论】:

  • 查看Map。将单词映射到它们的使用计数。处理单词时更新计数。
  • 地图?那是什么 ?对不起,我是初学者,所以我不知道地图
  • 这就是我说调查的原因。 java.util.Map 及其实现。
  • 这是你的作业吗??
  • geeksforgeeks.org/remove-all-duplicates-from-the-input-string 便于实施..虽然代码在 c 中。

标签: java string extract words


【解决方案1】:

使用以单词为键并计为值的映射,像这样

    Map<String, Integer> map = new HashMap<>();
    for (String w : words) {
        Integer n = map.get(w);
        n = (n == null) ? 1 : ++n;
        map.put(w, n);
    }

如果您不允许使用 java.util,那么您可以使用一些排序算法对 arr 进行排序并执行此操作

    String[] words = new String[arr.length];
    int[] counts = new int[arr.length];
    words[0] = words[0];
    counts[0] = 1;
    for (int i = 1, j = 0; i < arr.length; i++) {
        if (words[j].equals(arr[i])) {
            counts[j]++;
        } else {
            j++;
            words[j] = arr[i];
            counts[j] = 1;
        }
    }

自 Java 8 以来使用 ConcurrentHashMap 的有趣解决方案

    ConcurrentMap<String, Integer> m = new ConcurrentHashMap<>();
    m.compute("x", (k, v) -> v == null ? 1 : v + 1);

【讨论】:

  • 有没有其他方法可以做到这一点,因为对于我的考试,我不允许使用 java.utill
  • 好的,看看我的无地图版本
  • @EvgeniyDorofeev,感谢逻辑看起来非常好,但“arr”在哪里定义?
  • @EvgeniyDorofeev 这个词对我来说真的很好,但我对这里的语法感到困惑:n = (n == null)? 1:++n;我是 Java 新手,您能解释一下它是如何工作的或告诉我在哪里可以找到吗?
  • @user25976 这就是所谓的三元运算符。这就像一个 if-then-else 语句。表示如下: (boolean condition)?(then):(else) 在这种情况下,我们正在检查n是否等于null,如果这个条件为真,那么我们将n的值设置为1。如果它为假,那么我们将 n 的值预加一。
【解决方案2】:

在 Java 8 中,您可以用两行简单的代码编写它!此外,您还可以利用并行计算。

这是最好的方法:

Stream<String> stream = Stream.of(text.toLowerCase().split("\\W+")).parallel();

Map<String, Long> wordFreq = stream
     .collect(Collectors.groupingBy(String::toString,Collectors.counting()));

【讨论】:

    【解决方案3】:

    试试这个

    public class Main
    {
    
        public static void main(String[] args)
        {       
            String text = "the quick brown fox jumps fox fox over the lazy dog brown";
            String[] keys = text.split(" ");
            String[] uniqueKeys;
            int count = 0;
            System.out.println(text);
            uniqueKeys = getUniqueKeys(keys);
    
            for(String key: uniqueKeys)
            {
                if(null == key)
                {
                    break;
                }           
                for(String s : keys)
                {
                    if(key.equals(s))
                    {
                        count++;
                    }               
                }
                System.out.println("Count of ["+key+"] is : "+count);
                count=0;
            }
        }
    
        private static String[] getUniqueKeys(String[] keys)
        {
            String[] uniqueKeys = new String[keys.length];
    
            uniqueKeys[0] = keys[0];
            int uniqueKeyIndex = 1;
            boolean keyAlreadyExists = false;
    
            for(int i=1; i<keys.length ; i++)
            {
                for(int j=0; j<=uniqueKeyIndex; j++)
                {
                    if(keys[i].equals(uniqueKeys[j]))
                    {
                        keyAlreadyExists = true;
                    }
                }           
    
                if(!keyAlreadyExists)
                {
                    uniqueKeys[uniqueKeyIndex] = keys[i];
                    uniqueKeyIndex++;               
                }
                keyAlreadyExists = false;
            }       
            return uniqueKeys;
        }
    }
    

    输出:

    the quick brown fox jumps fox fox over the lazy dog brown
    Count of [the] is : 2
    Count of [quick] is : 1
    Count of [brown] is : 2
    Count of [fox] is : 3
    Count of [jumps] is : 1
    Count of [over] is : 1
    Count of [lazy] is : 1
    Count of [dog] is : 1
    

    【讨论】:

    • 这算字母吗?
    • 97 是 a 的 ascii,以此类推 122 是 z 的 ascii。
    • 我不想这样做,我想计算单词而不是字母
    【解决方案4】:
    import java.util.*;
    
    public class WordCounter {
    
        public static void main(String[] args) {
    
            String s = "this is a this is this a this yes this is a this what it may be i do not care about this";
            String a[] = s.split(" ");
            Map<String, Integer> words = new HashMap<>();
            for (String str : a) {
                if (words.containsKey(str)) {
                    words.put(str, 1 + words.get(str));
                } else {
                    words.put(str, 1);
                }
            }
            System.out.println(words);
        }
    }
    

    输出: {a=3, be=1, may=1, yes=1, this=7, about=1, i=1, is=3, it=1, do=1, not=1, what=1, care =1}

    【讨论】:

      【解决方案5】:

      从 Java 10 开始,您可以使用以下内容:

      import java.util.Arrays;
      import java.util.stream.Collectors;
      
      public class StringFrequencyMap {
          public static void main(String... args){
              String[] wordArray = {"One", "One", "Two","Three", "Two", "two"};
              var freq = Arrays.stream(wordArray)
                               .collect(Collectors.groupingBy(x -> x, Collectors.counting()));
              System.out.println(freq);
          }
      }
      

      输出:

      {One=2, two=1, Two=2, Three=1}
      

      【讨论】:

      • 虽然有效,但新的“var”在 Java 中看起来很奇怪 :-)
      【解决方案6】:

      你可以试试这个

      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);
          }
      }
      

      【讨论】:

        【解决方案7】:
        package naresh.java;
        import java.util.HashMap;
        import java.util.HashSet;
        import java.util.Set;
        
        public class StringWordDuplicates {
        
            static void duplicate(String inputString){
        
                HashMap<String, Integer> wordCount = new HashMap<String,Integer>();
                String[] words = inputString.split(" ");
        
                for(String word : words){
                    if(wordCount.containsKey(word)){
                        wordCount.put(word, wordCount.get(word)+1);             
                    }
                    else{
                        wordCount.put(word, 1);
                    }
                }
                //Extracting of all keys of word count
                Set<String> wordsInString = wordCount.keySet();
        
                for(String word : wordsInString){
                    if(wordCount.get(word)>1){
                        System.out.println(word+":"+wordCount.get(word));
                    }
                }
        
            }
            public static void main(String args[]){
                duplicate("I am Java Programmer and IT Server Programmer with Java as Best Java lover");
        
            }
        }
        

        【讨论】:

          【解决方案8】:
          class find
          {
              public static void main(String nm,String w)
              {
                  int l,i;
                  int c=0;
          
          
                  l=nm.length();String b="";
          
                  for(i=0;i<l;i++)
                  {
                      char d=nm.charAt(i);
                      if(d!=' ')
                      {
                          b=b+d;
                      }
                      if(d==' ')
                      {
                          if(b.compareTo(w)==0)
                          {
                              c++;
          
                          } 
                         b="";           
                      }        
                  }       
                  System.out.println(c);
              }
          }
          

          【讨论】:

            【解决方案9】:
            public class wordFrequency {
                private static Scanner scn;
            
                public static void countwords(String sent) {
                    sent = sent.toLowerCase().replaceAll("[^a-z ]", "");
                    ArrayList<String> arr = new ArrayList<String>();
                    String[] sentarr = sent.split(" ");
                    Map<String, Integer> a = new HashMap<String, Integer>();
                    for (String word : sentarr) {
                        arr.add(word);
                    }
                    for (String word : arr) {
                        int count = Collections.frequency(arr, word);
                        a.put(word, count);
                    }
                    for (String key : a.keySet()) {
                        System.out.println(key + " = " + a.get(key));
                    }
                }
            
                public static void main(String[] args) {
                    scn = new Scanner(System.in);
                    System.out.println("Enter sentence:");
                    String inp = scn.nextLine();
                    countwords(inp);
                }
            
            }
            

            【讨论】:

              【解决方案10】:

              确定文件中单词的频率。

              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 );
              

              }

              【讨论】:

                【解决方案11】:

                下面的程序找到频率,对它进行相应的排序,然后打印出来。

                下面是按频率分组的输出:

                0-10:
                       The   2
                       Is    4
                11-20:
                       Have 13
                       Done 15
                

                这是我的程序:

                package com.company;
                import java.io.*;
                import java.util.*;
                import java.lang.*;
                
                /**
                 * Created by ayush on 12/3/17.
                 */
                
                public class Linked {
                
                    public static void main(String args[]) throws IOException {
                
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(System.in));
                        System.out.println("Enter the sentence");
                        String st = br.readLine();
                        st=st.trim();
                        st = st + " ";
                        int count = lengthx(st);
                        System.out.println(count);
                        String arr[] = new String[count];
                        int p = 0;
                        int c = 0;
                
                        for (int i = 0; i < st.length(); i++) {
                            if (st.charAt(i) == ' ') {
                                arr[p] = st.substring(c,i);
                                System.out.println(arr[p]);
                                c = i + 1;
                                p++;
                            }
                        }
                        Map<String, Integer> map = new HashMap<>();
                
                        for (String w : arr) {
                            Integer n = map.get(w);
                            n = (n == null) ? 1 : ++n;
                            map.put(w, n);
                        }
                        for (String key : map.keySet()) {
                            System.out.println(key + " = " + map.get(key));
                        }
                
                        Set<Map.Entry<String, Integer>> entries = map.entrySet();
                
                        Comparator<Map.Entry<String, Integer>> valueComparator = new Comparator<Map.Entry<String,Integer>>() {
                
                            @Override
                            public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
                                Integer v1 = e1.getValue();
                                Integer v2 = e2.getValue();
                                return v1.compareTo(v2); }
                        };
                
                        List<Map.Entry<String, Integer>> listOfEntries = new ArrayList<Map.Entry<String, Integer>>(entries);
                        Collections.sort(listOfEntries, valueComparator);
                
                        LinkedHashMap<String, Integer> sortedByValue = new LinkedHashMap<String, Integer>(listOfEntries.size());
                
                        for(Map.Entry<String, Integer> entry : listOfEntries){
                
                            sortedByValue.put(entry.getKey(), entry.getValue());
                        }
                
                        for(Map.Entry<String, Integer> entry : listOfEntries){
                
                            sortedByValue.put(entry.getKey(), entry.getValue());
                        }
                
                        System.out.println("HashMap after sorting entries by values ");
                        Set<Map.Entry<String, Integer>> entrySetSortedByValue = sortedByValue.entrySet();
                        for(Map.Entry<String, Integer> mapping : entrySetSortedByValue){
                            System.out.println(mapping.getKey() + " ==> " + mapping.getValue());
                        }
                
                
                    }
                
                    static int lengthx(String a) {
                        int count = 0;
                        for (int j = 0; j < a.length(); j++) {
                            if (a.charAt(j) == ' ') {
                                count++;
                            }
                        }
                        return count;
                    }
                }
                

                【讨论】:

                • 我现在只需要以组格式输出,知道怎么做。提前致谢。
                【解决方案12】:
                import java.io.*;
                
                class Linked {
                
                    public static void main(String args[]) throws IOException {
                
                        BufferedReader br = new BufferedReader(
                            new InputStreamReader(System.in));
                        System.out.println("Enter the sentence");
                        String st = br.readLine();
                        st = st + " ";
                        int a = lengthx(st);
                        String arr[] = new String[a];
                        int p = 0;
                        int c = 0;
                
                        for (int j = 0; j < st.length(); j++) {
                            if (st.charAt(j) == ' ') {
                                arr[p++] = st.substring(c,j);
                                c = j + 1;
                            }
                        }
                    }
                
                    static int lengthx(String a) {
                        int p = 0;
                        for (int j = 0; j < a.length(); j++) {
                            if (a.charAt(j) == ' ') {
                                p++;
                            }
                        }
                        return p;
                    }
                }
                

                【讨论】:

                  【解决方案13】:

                  只需使用 Java 8 Stream 收集器 groupby 函数:

                      import java.util.function.Function;
                      import java.util.stream.Collectors;  
                  
                      static String[] COUNTRY_NAMES 
                    = { "China", "Australia", "India", "USA", "USSR", "UK", "China", 
                    "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
                  
                      Map<String, Long> result = Stream.of(COUNTRY_NAMES).collect(
                              Collectors.groupingBy(Function.identity(), Collectors.counting()));
                  

                  【讨论】:

                    【解决方案14】:

                    java 8中list元素的计数频率

                    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);
                    

                    注意: 对于字符串频率计数,拆分字符串并将其转换为列表并使用流进行计数 => (Map frequencyMap)*

                    Check below link

                    【讨论】:

                      【解决方案15】:
                          String s[]=st.split(" ");
                          String sf[]=new String[s.length];
                          int count[]=new int[s.length];
                          sf[0]=s[0];
                          int j=1;
                          count[0]=1;
                          for(int i=1;i<s.length;i++)
                          {
                              int t=j-1;
                              while(t>=0)
                              {
                      
                                  if(s[i].equals(sf[t]))
                                  {
                                      count[t]++;
                                      break;
                                  }
                                  t--;
                              }
                              if(t<0)
                              {
                                  sf[j]=s[i];
                                  count[j]++;
                                  j++;
                              }
                          }
                      

                      【讨论】:

                        【解决方案16】:

                        为这个问题创建了一个简单易懂的解决方案,涵盖所有测试用例-

                        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-------
                            }
                        }
                        

                        【讨论】:

                          【解决方案17】:
                          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);
                                  }
                              }
                          
                          }
                          

                          【讨论】:

                          • 欢迎来到 Stack Overflow!虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
                          【解决方案18】:
                          public class TestSplit {
                          
                              public static void main(String[] args) {
                                      String input="Find the repeated word which is repeated in this string";
                                      List<String> output= (List) Arrays.asList(input.split(" "));
                          
                                      for(String str: output) {
                                              int occurrences = Collections.frequency(output, str);
                                              System.out.println("Occurence of " + str+ " is "+occurrences);
                                      }
                          
                                      System.out.println(output);
                              }
                          
                          }
                          

                          【讨论】:

                            【解决方案19】:

                            请尝试这些可能对你有帮助

                                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;
                                }
                            

                            【讨论】:

                              猜你喜欢
                              • 2023-03-22
                              • 1970-01-01
                              • 1970-01-01
                              • 2015-08-18
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              相关资源
                              最近更新 更多