2011-01-27 69 views
8

Necesito encontrar palabras repetidas en una cadena, y luego contar cuántas veces se repitieron. Así que, básicamente, si la cadena de entrada es la siguiente:Encontrar palabras repetidas en una cadena y contar las repeticiones

String s = "House, House, House, Dog, Dog, Dog, Dog"; 

Necesito crear una nueva lista de cadenas sin repeticiones y guardar en otro lugar de la cantidad de repeticiones para cada palabra, como por ejemplo:

nueva cadena: " casa, el perro"

Nueva INT matriz: [3, 4]

¿hay una manera de hacer esto fácilmente con Java? He logrado separar la cadena usando s.split(), pero ¿cómo puedo contar las repeticiones y eliminarlas en la nueva cadena? ¡Gracias!

Respuesta

14

Tienes el trabajo duro hecho. Ahora sólo puede utilizar un Map para contar las apariciones:

Map<String, Integer> occurrences = new HashMap<String, Integer>(); 

for (String word : splitWords) { 
    Integer oldCount = occurrences.get(word); 
    if (oldCount == null) { 
     oldCount = 0; 
    } 
    occurrences.put(word, oldCount + 1); 
} 

Usando map.get(word) le dirá muchas veces que ocurre una palabra. Puede construir una nueva lista por iteración a través de map.keySet():

for (String word : occurrences.keySet()) { 
    //do something with word 
} 

Tenga en cuenta que el orden de lo que salga de keySet es arbitraria. Si necesita ordenar las palabras por la primera vez que aparecen en su cadena de entrada, debe usar un LinkedHashMap en su lugar.

+0

usando map.get (palabra) devuelve nulo. aquí está la documentación: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html ---- EDITACIÓN MÁS TARDE: vi que tu clave es String, así que sí, funciona , mi error. –

0

Si esto es una tarea, entonces todo lo que puedo decir es: use String.split() y HashMap<String,Integer>.

(Veo que has encontrado split() ya. Eres lo largo de las líneas de la derecha a continuación.)

3

Como han mencionado otros Usar cadena :: split(), seguido por algún mapa (HashMap o LinkedHashMap) y luego fusiona tu resultado. Para completar, poner el código.

import java.util.*; 

public class Genric<E> 
{ 
    public static void main(String[] args) 
    { 
     Map<String, Integer> unique = new LinkedHashMap<String, Integer>(); 
     for (String string : "House, House, House, Dog, Dog, Dog, Dog".split(", ")) { 
      if(unique.get(string) == null) 
       unique.put(string, 1); 
      else 
       unique.put(string, unique.get(string) + 1); 
     } 
     String uniqueString = join(unique.keySet(), ", "); 
     List<Integer> value = new ArrayList<Integer>(unique.values()); 

     System.out.println("Output = " + uniqueString); 
     System.out.println("Values = " + value); 

    } 

    public static String join(Collection<String> s, String delimiter) { 
     StringBuffer buffer = new StringBuffer(); 
     Iterator<String> iter = s.iterator(); 
     while (iter.hasNext()) { 
      buffer.append(iter.next()); 
      if (iter.hasNext()) { 
       buffer.append(delimiter); 
      } 
     } 
     return buffer.toString(); 
    } 
} 

nueva cadena es Output = House, Dog

int matriz (o más bien la lista) Values = [3, 4] (se puede utilizar la Lista :: toArray) para obtener una matriz.

+0

Hola @ Favonius. Quiero cargar las cadenas de un archivo de texto y aplicar su código. Como este, quiero obtener 2000 + archivos de texto, cada uno aplica su código por separado y sale ... ¿Es esto posible? –

0
/*count no of Word in String using TreeMap we can use HashMap also but word will not display in sorted order */ 

import java.util.*; 

public class Genric3 
{ 
    public static void main(String[] args) 
    { 
     Map<String, Integer> unique = new TreeMap<String, Integer>(); 
     String string1="Ram:Ram: Dog: Dog: Dog: Dog:leela:leela:house:house:shayam"; 
     String string2[]=string1.split(":"); 

     for (int i=0; i<string2.length; i++) 
     { 
      String string=string2[i]; 
      unique.put(string,(unique.get(string) == null?1:(unique.get(string)+1))); 
     } 

     System.out.println(unique); 
    } 
}  
0

Puede utilizar la estructura de datos Árbol de prefijos (trie) para almacenar palabras y realizar un seguimiento del recuento de palabras dentro del Nodo de árbol de prefijo.

#define ALPHABET_SIZE 26 
    // Structure of each node of prefix tree 
    struct prefix_tree_node { 
    prefix_tree_node() : count(0) {} 
    int count; 
    prefix_tree_node *child[ALPHABET_SIZE]; 
    }; 
    void insert_string_in_prefix_tree(string word) 
    { 
    prefix_tree_node *current = root; 
    for(unsigned int i=0;i<word.size();++i){ 
     // Assuming it has only alphabetic lowercase characters 
      // Note ::::: Change this check or convert into lower case 
    const unsigned int letter = static_cast<int>(word[i] - 'a'); 

     // Invalid alphabetic character, then continue 
     // Note :::: Change this condition depending on the scenario 
     if(letter > 26) 
     throw runtime_error("Invalid alphabetic character"); 

     if(current->child[letter] == NULL) 
     current->child[letter] = new prefix_tree_node(); 

     current = current->child[letter]; 
    } 
    current->count++; 
    // Insert this string into Max Heap and sort them by counts 
} 

    // Data structure for storing in Heap will be something like this 
    struct MaxHeapNode { 
     int count; 
     string word; 
    }; 

Después de insertar todas las palabras, debe imprimir la palabra y contar al iterar Maxheap.

0
//program to find number of repeating characters in a string 
//Developed by Subash<[email protected]> 


import java.util.Scanner; 

public class NoOfRepeatedChar 

{ 

    public static void main(String []args) 

    { 

//input through key board 

Scanner sc = new Scanner(System.in); 

System.out.println("Enter a string :"); 

String s1= sc.nextLine(); 


    //formatting String to char array 

    String s2=s1.replace(" ",""); 
    char [] ch=s2.toCharArray(); 

    int counter=0; 

    //for-loop tocompare first character with the whole character array 

    for(int i=0;i<ch.length;i++) 
    { 
     int count=0; 

     for(int j=0;j<ch.length;j++) 
     { 
      if(ch[i]==ch[j]) 
       count++; //if character is matching with others 
     } 
     if(count>1) 
     { 
      boolean flag=false; 

      //for-loop to check whether the character is already refferenced or not 
      for (int k=i-1;k>=0 ;k--) 
      { 
       if(ch[i] == ch[k]) //if the character is already refferenced 
        flag=true; 
      } 
      if(!flag) //if(flag==false) 
       counter=counter+1; 
     } 
    } 
    if(counter > 0) //if there is/are any repeating characters 
      System.out.println("Number of repeating charcters in the given string is/are " +counter); 
    else 
      System.out.println("Sorry there is/are no repeating charcters in the given string"); 
    } 
} 
3

Prueba de esto,

public class DuplicateWordSearcher { 
@SuppressWarnings("unchecked") 
public static void main(String[] args) { 

    String text = "a r b k c d se f g a d f s s f d s ft gh f ws w f v x s g h d h j j k f sd j e wed a d f"; 

    List<String> list = Arrays.asList(text.split(" ")); 

    Set<String> uniqueWords = new HashSet<String>(list); 
    for (String word : uniqueWords) { 
     System.out.println(word + ": " + Collections.frequency(list, word)); 
    } 
} 

}

0
public static void main(String[] args) { 
    String s="sdf sdfsdfsd sdfsdfsd sdfsdfsd sdf sdf sdf "; 
    String st[]=s.split(" "); 
    System.out.println(st.length); 
    Map<String, Integer> mp= new TreeMap<String, Integer>(); 
    for(int i=0;i<st.length;i++){ 

     Integer count=mp.get(st[i]); 
     if(count == null){ 
      count=0; 
     }   
     mp.put(st[i],++count); 
    } 
    System.out.println(mp.size()); 
    System.out.println(mp.get("sdfsdfsd")); 


} 
0

Si pasa un argumento de cadena contará la repetición de cada palabra

/** 
* @param string 
* @return map which contain the word and value as the no of repatation 
*/ 
public Map findDuplicateString(String str) { 
    String[] stringArrays = str.split(" "); 
    Map<String, Integer> map = new HashMap<String, Integer>(); 
    Set<String> words = new HashSet<String>(Arrays.asList(stringArrays)); 
    int count = 0; 
    for (String word : words) { 
     for (String temp : stringArrays) { 
      if (word.equals(temp)) { 
       ++count; 
      } 
     } 
     map.put(word, count); 
     count = 0; 
    } 

    return map; 

} 

de salida:

Word1=2, word2=4, word2=1,. . . 
0
import java.util.HashMap; 
import java.util.LinkedHashMap; 

public class CountRepeatedWords { 

    public static void main(String[] args) { 
      countRepeatedWords("Note that the order of what you get out of keySet is arbitrary. If you need the words to be sorted by when they first appear in your input String, you should use a LinkedHashMap instead."); 
    } 

    public static void countRepeatedWords(String wordToFind) { 
     String[] words = wordToFind.split(" "); 
     HashMap<String, Integer> wordMap = new LinkedHashMap<String, Integer>(); 

     for (String word : words) { 
      wordMap.put(word, 
       (wordMap.get(word) == null ? 1 : (wordMap.get(word) + 1))); 
     } 

      System.out.println(wordMap); 
    } 

} 
0

espero que esto le ayude

pública countInPara void (String str) {

Map<Integer,String> strMap = new HashMap<Integer,String>(); 
    List<String> paraWords = Arrays.asList(str.split(" ")); 
    Set<String> strSet = new LinkedHashSet<>(paraWords); 
    int count; 

    for(String word : strSet) { 
     count = Collections.frequency(paraWords, word); 
     strMap.put(count, strMap.get(count)==null ? word : strMap.get(count).concat(","+word)); 
    } 

    for(Map.Entry<Integer,String> entry : strMap.entrySet()) 
     System.out.println(entry.getKey() +" :: "+ entry.getValue()); 
} 
1
public class StringsCount{ 

    public static void main(String args[]) { 

     String value = "This is testing Program testing Program"; 

     String item[] = value.split(" "); 

     HashMap<String, Integer> map = new HashMap<>(); 

     for (String t : item) { 
      if (map.containsKey(t)) { 
       map.put(t, map.get(t) + 1); 

      } else { 
       map.put(t, 1); 
      } 
     } 
     Set<String> keys = map.keySet(); 
     for (String key : keys) { 
      System.out.println(key); 
      System.out.println(map.get(key)); 
     } 

    } 
} 
0
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.HashMap; 
import java.util.HashSet; 
import java.util.List; 
import java.util.Map; 
import java.util.Set; 

public class DuplicateWord { 

    public static void main(String[] args) { 
     String para = "this is what it is this is what it can be"; 
     List <String> paraList = new ArrayList <String>(); 
     paraList = Arrays.asList(para.split(" ")); 
     System.out.println(paraList); 
     int size = paraList.size(); 

     int i = 0; 
     Map < String, Integer > duplicatCountMap = new HashMap < String, Integer >(); 
     for (int j = 0; size > j; j++) { 
      int count = 0; 
      for (i = 0; size > i; i++) { 
       if (paraList.get(j).equals(paraList.get(i))) { 
        count++; 
        duplicatCountMap.put(paraList.get(j), count); 
       } 

      } 

     } 
     System.out.println(duplicatCountMap); 
     List <Integer> myCountList = new ArrayList < >(); 
     Set <String> myValueSet = new HashSet < >(); 
     for (Map.Entry < String, Integer > entry: duplicatCountMap.entrySet()) { 
      myCountList.add(entry.getValue()); 
      myValueSet.add(entry.getKey()); 
     } 
     System.out.println(myCountList); 
     System.out.println(myValueSet); 
    } 

} 

de entrada: esto es lo que es esto es lo que puede ser

de salida:

[esto, es, qué, ella, es, esto, es, qué, que, puede, sea]

{puede = 1, lo = 2, sea = 1, este = 2, es = 3, it = 2}

[1, 2, 1, 2, 3, 2]

[puede, qué, ser, esto, es, él]

+0

esto no necesita un bucle anidado. un análisis sintáctico lineal sobre la matriz de palabras sería lo suficientemente bueno para verificar si existe una clave HashMap, incrementar, de lo contrario, agregar una entrada y establecer el valor en cero –

0
import java.util.HashMap; 
import java.util.Scanner; 
public class class1 { 
public static void main(String[] args) { 
    Scanner in = new Scanner(System.in); 
    String inpStr = in.nextLine(); 
    int key; 

    HashMap<String,Integer> hm = new HashMap<String,Integer>(); 
    String[] strArr = inpStr.split(" "); 

    for(int i=0;i<strArr.length;i++){ 
     if(hm.containsKey(strArr[i])){ 
      key = hm.get(strArr[i]); 
      hm.put(strArr[i],key+1); 

     } 
     else{ 
      hm.put(strArr[i],1); 
     } 
    } 
    System.out.println(hm); 
} 

}

+0

Pocas palabras serían mejores para explicar su código, en lugar de solo el código. – surajsn

+0

1. En Hashmap, las palabras serán la clave y la aparición tendrá valor. Si estamos poniendo palabra por primera vez en un mapa hash y el valor relacionado será 1. De lo contrario, aumentamos el valor en 1 cada vez que ponemos la misma palabra. –

+0

Por favor, ponga esto en la sección de respuestas, no en la sección de comentarios. – surajsn

0

Utilice el siguiente código. Es el más simple según mi análisis. Espero que te guste:

import java.util.Arrays; 
import java.util.Collections; 
import java.util.HashMap; 
import java.util.HashSet; 
import java.util.List; 
import java.util.Scanner; 
import java.util.Set; 

public class MostRepeatingWord { 

    String mostRepeatedWord(String s){ 
     String[] splitted = s.split(" "); 
     List<String> listString = Arrays.asList(splitted); 
     Set<String> setString = new HashSet<String>(listString); 
     int count = 0; 
     int maxCount = 1; 
     String maxRepeated = null; 
     for(String inp: setString){ 
      count = Collections.frequency(listString, inp); 
      if(count > maxCount){ 
       maxCount = count; 
       maxRepeated = inp; 
      } 
     } 
     return maxRepeated; 
    } 
    public static void main(String[] args) 
    {  
     System.out.println("Enter The Sentence: "); 
     Scanner s = new Scanner(System.in); 
     String input = s.nextLine(); 
     MostRepeatingWord mrw = new MostRepeatingWord(); 
     System.out.println("Most repeated word is: " + mrw.mostRepeatedWord(input)); 

    } 
} 
0
package day2; 

import java.util.ArrayList; 
import java.util.HashMap;`enter code here` 
import java.util.List; 

public class DuplicateWords { 

    public static void main(String[] args) { 
     String S1 = "House, House, House, Dog, Dog, Dog, Dog"; 
     String S2 = S1.toLowerCase(); 
     String[] S3 = S2.split("\\s"); 

     List<String> a1 = new ArrayList<String>(); 
     HashMap<String, Integer> hm = new HashMap<>(); 

     for (int i = 0; i < S3.length - 1; i++) { 

      if(!a1.contains(S3[i])) 
      { 
       a1.add(S3[i]); 
      } 
      else 
      { 
       continue; 
      } 

      int Count = 0; 

      for (int j = 0; j < S3.length - 1; j++) 
      { 
       if(S3[j].equals(S3[i])) 
       { 
        Count++; 
       } 
      } 

      hm.put(S3[i], Count); 
     } 

     System.out.println("Duplicate Words and their number of occurrences in String S1 : " + hm); 
    } 
} 
0
public class Counter { 

private static final int COMMA_AND_SPACE_PLACE = 2; 

private String mTextToCount; 
private ArrayList<String> mSeparateWordsList; 

public Counter(String mTextToCount) { 
    this.mTextToCount = mTextToCount; 

    mSeparateWordsList = cutStringIntoSeparateWords(mTextToCount); 
} 

private ArrayList<String> cutStringIntoSeparateWords(String text) 
{ 
    ArrayList<String> returnedArrayList = new ArrayList<>(); 


    if(text.indexOf(',') == -1) 
    { 
     returnedArrayList.add(text); 
     return returnedArrayList; 
    } 

    int position1 = 0; 
    int position2 = 0; 

    while(position2 < text.length()) 
    { 
     char c = ','; 
     if(text.toCharArray()[position2] == c) 
     { 
      String tmp = text.substring(position1, position2); 
      position1 += tmp.length() + COMMA_AND_SPACE_PLACE; 
      returnedArrayList.add(tmp); 
     } 
     position2++; 
    } 

    if(position1 < position2) 
    { 
     returnedArrayList.add(text.substring(position1, position2)); 
    } 

    return returnedArrayList; 
} 

public int[] countWords() 
{ 
    if(mSeparateWordsList == null) return null; 


    HashMap<String, Integer> wordsMap = new HashMap<>(); 

    for(String s: mSeparateWordsList) 
    { 
     int cnt; 

     if(wordsMap.containsKey(s)) 
     { 
      cnt = wordsMap.get(s); 
      cnt++; 
     } else { 
      cnt = 1; 
     } 
     wordsMap.put(s, cnt); 
    }     
    return printCounterResults(wordsMap); 
} 

private int[] printCounterResults(HashMap<String, Integer> m) 
{   
    int index = 0; 
    int[] returnedIntArray = new int[m.size()]; 

    for(int i: m.values()) 
    { 
     returnedIntArray[index] = i; 
     index++; 
    } 

    return returnedIntArray; 

} 

}

0
//program to find number of repeating characters in a string 
//Developed by Rahul Lakhmara 

import java.util.*; 

public class CountWordsInString { 
    public static void main(String[] args) { 
     String original = "I am rahul am i sunil so i can say am i"; 
     // making String type of array 
     String[] originalSplit = original.split(" "); 
     // if word has only one occurrence 
     int count = 1; 
     // LinkedHashMap will store the word as key and number of occurrence as 
     // value 
     Map<String, Integer> wordMap = new LinkedHashMap<String, Integer>(); 

     for (int i = 0; i < originalSplit.length - 1; i++) { 
      for (int j = i + 1; j < originalSplit.length; j++) { 
       if (originalSplit[i].equals(originalSplit[j])) { 
        // Increment in count, it will count how many time word 
        // occurred 
        count++; 
       } 
      } 
      // if word is already present so we will not add in Map 
      if (wordMap.containsKey(originalSplit[i])) { 
       count = 1; 
      } else { 
       wordMap.put(originalSplit[i], count); 
       count = 1; 
      } 
     } 

     Set word = wordMap.entrySet(); 
     Iterator itr = word.iterator(); 
     while (itr.hasNext()) { 
      Map.Entry map = (Map.Entry) itr.next(); 
      // Printing 
      System.out.println(map.getKey() + " " + map.getValue()); 
     } 
    } 
} 
+0

Ponle un poco más de explicación a tu respuesta, no solo el código. –

0
public static void main(String[] args){ 
    String string = "elamparuthi, elam, elamparuthi"; 
    String[] s = string.replace(" ", "").split(","); 
    String[] op; 
    String ops = ""; 

    for(int i=0; i<=s.length-1; i++){ 
     if(!ops.contains(s[i]+"")){ 
      if(ops != "")ops+=", "; 
      ops+=s[i]; 
     } 

    } 
    System.out.println(ops); 
} 
+0

¡Bienvenido a StackOverflow! Tómese un momento para leer la página de ayuda sobre [cómo hacer preguntas] (http://stackoverflow.com/help/how-to-ask). ¿En qué se diferencia su respuesta de todas las que ya se proporcionaron? – avojak

1

Se puede ayudar de alguna manera.

String st="I am am not the one who is thinking I one thing at time"; 
String []ar = st.split("\\s"); 
Map<String, Integer> mp= new HashMap<String, Integer>(); 
int count=0; 

for(int i=0;i<ar.length;i++){ 
    count=0; 

    for(int j=0;j<ar.length;j++){ 
     if(ar[i].equals(ar[j])){ 
     count++;     
     } 
    } 

    mp.put(ar[i], count); 
} 

System.out.println(mp); 
0

En este caso, son los pasos para el recuento de palabras repetidas en una cadena

  1. Crear HashMap vacío de tipo String & Entero
  2. dividir la cadena utilizando el espacio de un delimitador y asignarlo a String []
  3. Iterar a través de String [] array después de dividir utilizando para cada bucle
  4. Nota: convertiremos todas las cadenas en minúsculas antes de comprobar si hay insensibilidad de mayúsculas y minúsculas propósito ive
  5. Compruebe si palabra en particular ya está presente en el HashMap utilizando el método containsKey (k) método de interfaz Mapa
  6. Si contiene, a continuación, aumentar el valor de recuento por 1 usando put (K, V) de Mapa
  7. de lo contrario
  8. inserte método put() de Mapa utilizando con valor de cuenta como 1
  9. Por último, mapa de impresión utilizando el método() de la interfaz de Map.Entry

programa completo conjunto de claves() o entrySet es poco largo, ya que está leyendo el contenido de la cadena desde el archivo local. Puede comprobar artículo en el siguiente enlace pegado

http://www.benchresources.net/count-and-print-number-of-repeated-word-occurrences-in-a-string-in-java/

0

For Strings sin espacio, podemos utilizar el código

private static void findRecurrence(String input) { 
    final Map<String, Integer> map = new LinkedHashMap<>(); 
    for(int i=0; i<input.length();) { 
     int pointer = i; 
     int startPointer = i; 
     boolean pointerHasIncreased = false; 
     for(int j=0; j<startPointer; j++){ 
      if(pointer<input.length() && input.charAt(j)==input.charAt(pointer) && input.charAt(j)!=32){ 
       pointer++; 
       pointerHasIncreased = true; 
      }else{ 
       if(pointerHasIncreased){ 
        break; 
       } 
      } 
     } 
     if(pointer - startPointer >= 2) { 
      String word = input.substring(startPointer, pointer); 
      if(map.containsKey(word)){ 
       map.put(word, map.get(word)+1); 
      }else{ 
       map.put(word, 1); 
      } 
      i=pointer; 
     }else{ 
      i++; 
     } 
    } 
    for(Map.Entry<String, Integer> entry : map.entrySet()){ 
     System.out.println(entry.getKey() + " = " + (entry.getValue()+1)); 
    } 
} 

mencionado a continuación pasar alguna entrada como "jajaja" o "ba na na "o" xxxyyyzzzxxxzzz "dan el resultado deseado.

Cuestiones relacionadas