web-dev-qa-db-ja.com

javaで文中の各単語の頻度を計算する

私は非常に基本的な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;
    }
}

私は各文字列を抽出して配列に格納しましたが、実際には問題は各「単語」が繰り返されるインスタンスの数をカウントする方法と、繰り返される単語が複数回表示されないように表示する方法です、あなたはこれで私を助けることができます1 ?

11
Sigma

Wordをキーとしてマップを使用し、値としてカウントします。

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

Java 8では、これを2つの簡単な行で記述できます!さらに、並列計算を利用できます。

これを行う最も美しい方法は次のとおりです。

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

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

これを試して

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

出力:{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}

3
AKT

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

これを試すことができます

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

ファイル内の単語の頻度を決定します。

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

次のプログラムは、頻度を見つけ、それに応じてソートし、印刷します。

以下は、頻度別にグループ化された出力です。

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

Java 8 Stream collectors groupby function:

    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

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

注:文字列の頻度カウントでは、文字列を分割してリストに変換し、カウント頻度のストリームを使用します=>(Map frequencyMap)*

リンクの下を確認

0
Narayana