web-dev-qa-db-fra.com

Calcul de la fréquence de chaque mot dans une phrase en java

J'écris un programme Java très basique qui calcule la fréquence de chaque mot dans une phrase jusqu'à présent, j'ai réussi à le faire beaucoup

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

J'ai extrait chaque chaîne et l'ai stockée dans un tableau. Le problème est maintenant de savoir comment compter le nombre d'occurrences où chaque 'mot' est répété et comment l'afficher pour que les mots répétés ne s'affichent pas plusieurs fois. Pouvez-vous m'aider dans cette tâche? un ?

11
Sigma

Utiliser une carte avec Word comme clé et compter comme valeur, quelque chose comme ça

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

si vous n'êtes pas autorisé à utiliser Java.util, vous pouvez alors trier arr en utilisant un algorithme de tri

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

Une solution intéressante avec ConcurrentHashMap depuis Java 8

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

En Java 8, vous pouvez écrire cela en deux lignes simples! De plus, vous pouvez tirer parti du calcul parallèle.

Voici la plus belle façon de faire ceci:

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

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

Essaye ça

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

Sortie:

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

Sortie: quoi = 1, soin = 1}

3
AKT

À partir de Java 10, vous pouvez utiliser les éléments suivants:

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

Sortie:

{One=2, two=1, Two=2, Three=1}
2
user2173372
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");

    }
}
1
Ramnaresh Mantri

Tu pourrais essayer ça

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);
    }
}
1
Nhan
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);
    }
}
0
mohd naeem khan
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);
    }

}
0
Rajesh NJ

Déterminez la fréquence des mots dans un fichier.

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
jsroyal
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;
    }
}
0
Mouhamad Read

Le programme suivant trouve la fréquence, la trie en conséquence et l’imprime.

Ci-dessous, la sortie regroupée par fréquence:

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

Voici mon programme:

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;
    }
}
0
Kumar Ayush

Utilisez simplement la fonction groupby de collecteurs Java 8 Stream: 

    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()));
0
Koenigsegg