2011-01-12 15 views
30

ho bisogno del mio programma Java di prendere una stringa del tipo:conversione di una stringa frase per un array di stringhe di parole in Java

"This is a sample sentence." 

e di trasformarlo in una matrice di stringhe come:

{"this","is","a","sample","sentence"} 

No periodi, o punteggiatura (preferibilmente). A proposito, la stringa di input è sempre una frase.

C'è un modo semplice per farlo che non vedo? O dobbiamo davvero cercare molto gli spazi e creare nuove stringhe dalle aree tra gli spazi (che sono le parole)?

+0

seguente Si consiglia inoltre di guardare la classe Splitter guava: http://guava-libraries.googlecode.com/svn/trunk /javadoc/com/google/common/base/Splitter.html – dkarp

risposta

44

String.split() farà la maggior parte di ciò che desideri. Potrebbe quindi essere necessario eseguire il loop delle parole per eliminare eventuali segni di punteggiatura.

Ad esempio:

String s = "This is a sample sentence."; 
String[] words = s.split("\\s+"); 
for (int i = 0; i < words.length; i++) { 
    // You may want to check for a non-word character before blindly 
    // performing a replacement 
    // It may also be necessary to adjust the character class 
    words[i] = words[i].replaceAll("[^\\w]", ""); 
} 
+6

Potresti aggiungere una spiegazione sull'espressione regolare che hai usato? – Marek

+1

http://docs.oracle.com/javase/tutorial/essential/regex/quant.html – user817129

5

La risposta più semplice e migliore che posso pensare è quello di utilizzare il seguente metodo definito sulla stringa java -

String[] split(String regex) 

e fare solo "Questo è un esempio frase ".split (" "). Poiché richiede un'espressione regolare, è possibile eseguire anche divisioni più complicate, che possono includere la rimozione della punteggiatura indesiderata e altri caratteri simili.

+0

Ragazzi questa è la soluzione più semplice se una frase non ha segni di punteggiatura. – sandalone

4

Utilizzare string.replace(".", "").replace(",", "").replace("?", "").replace("!","").split(' ') per suddividere il codice in un array senza punti, virgole, punti interrogativi o punti esclamativi. È possibile aggiungere/rimuovere tutte le chiamate sostitutive che si desidera.

+0

Corretto, che funziona bene per rimuovere la punteggiatura. – AnimatedRNG

+2

Piuttosto che chiamare sostituisci 4 volte, sarebbe meglio chiamarlo una volta con una regex che cattura uno dei 4 elementi. – jzd

3

Prova questo:

String[] stringArray = Pattern.compile("ian").split(
"This is a sample sentence" 
.replaceAll("[^\\p{Alnum}]+", "") //this will remove all non alpha numeric chars 
); 

for (int j=0; i<stringArray .length; j++) { 
    System.out.println(i + " \"" + stringArray [j] + "\""); 
} 
1

string.replaceAll() non funziona correttamente con impostazione internazionale diversa da predefinito. Almeno in jdk7u10.

questo esempio viene creato un dizionario di parole da file di testo con le finestre cirillico charset CP1251

public static void main (String[] args) { 
    String fileName = "Tolstoy_VoinaMir.txt"; 
    try { 
     List<String> lines = Files.readAllLines(Paths.get(fileName), 
               Charset.forName("CP1251")); 
     Set<String> words = new TreeSet<>(); 
     for (String s: lines) { 
      for (String w : s.split("\\s+")) { 
       w = w.replaceAll("\\p{Punct}",""); 
       words.add(w); 
      } 
     } 
     for (String w: words) { 
      System.out.println(w); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
5

Si può solo dividere la stringa come quella di utilizzare questo regolare espressione

String l = "sofia, malgré tout aimait : la laitue et le choux !" <br/> 
l.split("[[ ]*|[,]*|[\\.]*|[:]*|[/]*|[!]*|[?]*|[+]*]+"); 
+0

Buono per il francese. Puoi aggiungere alcune cose come: "[[] * | [,] * | [;] * | [:] * | ['] * | ['] * | [\\.] * | [:] * | [/] * | [!] * | [?] * | [+] *] + " – blackbox

2

seguito è un codice snippet che divide un sentenzioso in parola e dà il suo conto anche.

import java.util.HashMap; 
import java.util.Iterator; 
import java.util.Map; 

public class StringToword { 
public static void main(String[] args) { 
    String s="a a a A A"; 
    String[] splitedString=s.split(" "); 
    Map m=new HashMap(); 
    int count=1; 
    for(String s1 :splitedString){ 
     count=m.containsKey(s1)?count+1:1; 
      m.put(s1, count); 
     } 
    Iterator<StringToword> itr=m.entrySet().iterator(); 
    while(itr.hasNext()){ 
     System.out.println(itr.next());   
    } 
    } 

} 
1

Ho già postato questa risposta da qualche parte, lo farò di nuovo qui. Questa versione non utilizza alcun metodo principale incorporato. Hai ottenuto il char array, convertilo in una stringa. Spero che aiuti!

import java.util.Scanner; 

public class SentenceToWord 
{ 
    public static int getNumberOfWords(String sentence) 
    { 
     int counter=0; 
     for(int i=0;i<sentence.length();i++) 
     { 
      if(sentence.charAt(i)==' ') 
      counter++; 
     } 
     return counter+1; 
    } 

    public static char[] getSubString(String sentence,int start,int end) //method to give substring, replacement of String.substring() 
    { 
     int counter=0; 
     char charArrayToReturn[]=new char[end-start]; 
     for(int i=start;i<end;i++) 
     { 
      charArrayToReturn[counter++]=sentence.charAt(i); 
     } 
     return charArrayToReturn; 
    } 

    public static char[][] getWordsFromString(String sentence) 
    { 
     int wordsCounter=0; 
     int spaceIndex=0; 
     int length=sentence.length(); 
     char wordsArray[][]=new char[getNumberOfWords(sentence)][]; 
     for(int i=0;i<length;i++) 
     { 
      if(sentence.charAt(i)==' ' || i+1==length) 
      { 
      wordsArray[wordsCounter++]=getSubString(sentence, spaceIndex,i+1); //get each word as substring 
      spaceIndex=i+1; //increment space index 
      } 
     } 
     return wordsArray; //return the 2 dimensional char array 
    } 


    public static void main(String[] args) 
    { 
    System.out.println("Please enter the String"); 
    Scanner input=new Scanner(System.in); 
    String userInput=input.nextLine().trim(); 
    int numOfWords=getNumberOfWords(userInput); 
    char words[][]=new char[numOfWords+1][]; 
    words=getWordsFromString(userInput); 
    System.out.println("Total number of words found in the String is "+(numOfWords)); 
    for(int i=0;i<numOfWords;i++) 
    { 
     System.out.println(" "); 
     for(int j=0;j<words[i].length;j++) 
     { 
     System.out.print(words[i][j]);//print out each char one by one 
     } 
    } 
    } 

} 
9

È possibile utilizzare BreakIterator.getWordInstance per trovare tutte le parole in una stringa.

public static List<String> getWords(String text) { 
    List<String> words = new ArrayList<String>(); 
    BreakIterator breakIterator = BreakIterator.getWordInstance(); 
    breakIterator.setText(text); 
    int lastIndex = breakIterator.first(); 
    while (BreakIterator.DONE != lastIndex) { 
     int firstIndex = lastIndex; 
     lastIndex = breakIterator.next(); 
     if (lastIndex != BreakIterator.DONE && Character.isLetterOrDigit(text.charAt(firstIndex))) { 
      words.add(text.substring(firstIndex, lastIndex)); 
     } 
    } 

    return words; 
} 

prova:

public static void main(String[] args) { 
    System.out.println(getWords("A PT CR M0RT BOUSG SABN NTE TR/GB/(G) = RAND(MIN(XXX, YY + ABC))")); 
} 

Ouput:

[A, PT, CR, M0RT, BOUSG, SABN, NTE, TR, GB, G, RAND, MIN, XXX, YY, ABC] 
+0

non divide xy, cioè" divertente.Gioca ", restituisce funny.Does come 1 parola –

+0

E probabilmente non dovrebbe In inglese - il codice, purtroppo, non specifica un locale - le parole non sono divise per periodi. –

4

Provare a utilizzare il seguente:

String str = "This is a simple sentence"; 
String[] strgs = str.split(" "); 

che creerà una stringa ad ogni indice della matrice di stringhe usando lo spazio come punto di divisione.

5

Ora, questo può essere realizzato solo con split come ci vuole regex:

String s = "This is a sample sentence with []s."; 
String[] words = s.split("\\W+"); 

questo darà parole come: {"this","is","a","sample","sentence", "s"}

Il \\W+ corrisponderà tutti i caratteri non alfabetici che si verificano una o più volte . Quindi non c'è bisogno di sostituire. Puoi anche controllare altri modelli.

1

Un altro modo per farlo è StringTokenizer. es: -

public static void main(String[] args) { 

    String str = "This is a sample string"; 
    StringTokenizer st = new StringTokenizer(str," "); 
    String starr[]=new String[st.countTokens()]; 
    while (st.hasMoreElements()) { 
     starr[i++]=st.nextElement(); 
    } 
} 
0

È possibile utilizzare semplice codice

String str= "This is a sample sentence."; 
String[] words = str.split("[[ ]*|[//.]]"); 
for(int i=0;i<words.length;i++) 
System.out.print(words[i]+" ");