2008-11-09 43 views

Respuesta

17

Esto suena como el trabajo correcto para expresiones regulares. Aquí hay un código de Java para dar una idea, en caso de que no sabe cómo empezar:

String input = "Input text, with words, punctuation, etc. Well, it's rather short."; 
Pattern p = Pattern.compile("[\\w']+"); 
Matcher m = p.matcher(input); 

while (m.find()) { 
    System.out.println(input.substring(m.start(), m.end())); 
} 

El patrón [\w']+ coincidir todos los caracteres de texto, y el apóstrofe, múltiples veces. La cadena de ejemplo se imprimiría palabra por palabra. Eche un vistazo a Java Pattern class documentation para leer más.

+1

Tuve que cambiar ligeramente la expresión regular para no incluir números, guiones bajos y no tener palabras que comiencen con una comilla, pero de lo contrario, ¡bien! –

+0

Tuve que escapar de la \ w, así que: 'Pattern.compile (" [\\ w '] + ");' – ScrollerBlaster

+0

@ScrollerBlaster Eso es correcto. Lo arreglaré, gracias! – Tomalak

0

Puede intentar regexar, utilizando un patrón que haya creado, y ejecutar un conteo la cantidad de veces que se ha encontrado ese patrón.

3

Pseudocódigo se vería así:

create words, a list of words, by splitting the input by whitespace 
for every word, strip out whitespace and punctuation on the left and the right 

El código Python sería algo como esto:

words = input.split() 
words = [word.strip(PUNCTUATION) for word in words] 

donde

PUNCTUATION = ",. \n\t\\\"'][#*:" 

o cualquier otro carácter que desea eliminar.

Creo que Java tiene funciones equivalentes en la clase String: String .split().


salida de ejecutar este código en el texto que ya ha proporcionado en su enlace:

>>> print words[:100] 
['Project', "Gutenberg's", 'Manual', 'of', 'Surgery', 'by', 'Alexis', 
'Thomson', 'and', 'Alexander', 'Miles', 'This', 'eBook', 'is', 'for', 
'the', 'use', 'of', 'anyone', 'anywhere', 'at', 'no', 'cost', 'and', 
'with', 'almost', 'no', 'restrictions', 'whatsoever', 'You', 'may', 
'copy', 'it', 'give', 'it', 'away', 'or', 're-use', 'it', 'under', 
... etc etc. 
+0

La ventaja de este código a través de expresiones regulares es que se puede hacerse simplemente en un solo pase. –

+0

Sí Java tiene un método 'dividido', pero no tiene el equivalente del método 'strip'. –

1

Básicamente, que desea hacer coincidir

([A-Za-z]) + (' ([A-Za-z]) *)?

¿verdad?

3

He aquí una buena aproximación a su problema: Esta función recibe el texto como entrada y devuelve una matriz de todas las palabras dentro del texto dado

private ArrayList<String> get_Words(String SInput){ 

    StringBuilder stringBuffer = new StringBuilder(SInput); 
    ArrayList<String> all_Words_List = new ArrayList<String>(); 

    String SWord = ""; 
    for(int i=0; i<stringBuffer.length(); i++){ 
     Character charAt = stringBuffer.charAt(i); 
     if(Character.isAlphabetic(charAt) || Character.isDigit(charAt)){ 
      SWord = SWord + charAt; 
     } 
     else{ 
      if(!SWord.isEmpty()) all_Words_List.add(new String(SWord)); 
      SWord = ""; 
     } 

    } 

    return all_Words_List; 

} 
Cuestiones relacionadas