Foro de elhacker.net

Programación => PHP => Mensaje iniciado por: [u]nsigned en 22 Julio 2011, 18:35 pm



Título: Algoritmo Key Words
Publicado por: [u]nsigned en 22 Julio 2011, 18:35 pm
Bueno, el titulo no es muy descriptivo asi que me explicare.

Lo que quiero es saber si existe algun algoritmo(clase) que a partir de un texto dado, el contenido de una noticia por ejemplo, deduzca cuales podrian ser las posibles 'palabras claves' de dicha noticia. Estoy realizando un portal de noticias, y la idea es no tener que crear a 'mano' las palabras claves o TAGS para cada noticia...existira algo asi o una fomra de hacerlo?

Una forma se me ocurre seria buscando palabras poco usadas como nombres poprios de personas y ciudades, y tambien descartando palabras muy usadas como adjetivos, adverbios, proposiciones, etc..

Saludos


Título: Re: Algoritmo Key Words
Publicado por: madpitbull_99 en 22 Julio 2011, 19:43 pm
Supongo que con substr_count() (http://us3.php.net/manual/en/function.substr-count.php) se podría hacer algo.

Primero tendrías que meter todas las palabras en un array y después comprobar cuál es la que más se repite. Esas serán los "tags" de la noticia.




Título: Re: Algoritmo Key Words
Publicado por: #!drvy en 24 Julio 2011, 18:45 pm
Woah, bastante complicado lo veo  :-\
Aquí siempre tendria que estar el ojo humano o algo que se le acerque xD.

Así a primera vista podría acercarse un poquitin xD...
Código
  1. <?php
  2.    function findkeyword($text,$false,$min,$repeat){
  3.        $keyword = array();
  4.        $text = strtolower($text); // Covertir a letras minusculas
  5.        $words = explode(' ',$text); // Separar palabras
  6.  
  7.        foreach($words as $word){
  8.            if(preg_match('[\w{'.$min.',}]', $word)){ // Eliminar cualquier palabra menor de # chr.
  9.                $word = preg_replace('[\W]','',$word); // Eliminar cualquier chr excepto [a-z0-9]
  10.                if(!in_array($word,$false)){
  11.                    $findrepeat = substr_count($text, $word); // Contar repeticiones
  12.                    if($findrepeat > $repeat) {$keyword[] = $word;}// añadir a lista clave.
  13.                }
  14.            }
  15.        }
  16.        return array_unique($keyword);
  17.    }
  18.  
  19.    $repeat = 2; // minimas veces repetida para ser keyword.
  20.    $min = 3; // minima longitud de la palabra
  21.    $texto = ''; // texto para procesar
  22.    $false = array('you','me','he','and'); // etc.. lista de palabras que no estan admitidas.
  23.  
  24.    print_r(findkeyword($texto,$false,$min,$repeat));
  25. ?>

Suponiendo que el texto es
Código:
Silence! Stupid monkey. I kill you. You think you\'r better than 
my chicken! NO! Stupid monkey. My chicken is better than you! I kill you! Stupid monkey... my chicken is the best!

Las palabras claves que saca son:
Código:
Array ( [0] => stupid [1] => monkey [2] => chicken ) 


Saludos


Título: Re: Algoritmo Key Words
Publicado por: madpitbull_99 en 10 Agosto 2011, 23:12 pm
Lo he hecho de otra manera, aunque la función de drvy es más flexible (filtra palabras).


Código
  1. <?php
  2.  
  3. /*
  4. * Returns the most repetead words (llonger than $long)
  5. * given in a string
  6. *@author MadPitbull
  7. */
  8. function kWords($txt, $lim, $long = 3) {
  9.  
  10. $e = explode(" ", str_replace(array(",", "."), " ", strtolower($txt)));
  11. arsort($a); array_shift($a);
  12. $p = array_keys($a);
  13. for ($l = 0; $l < count($p); $l++) {
  14. if (strlen($p[$l]) >= $long ) {
  15. $f[] = $p[$l];
  16. }
  17. }
  18. for ($i = 0; $i < $lim; $i++) {
  19. $kW[] = $f[$i];
  20. }
  21. return $kW;
  22. }
  23.  
  24.  
  25. $txt = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
  26. $txt2 = "Silence! Stupid monkey. I kill you. You think you\'r better than my chicken! NO! Stupid monkey. My chicken is better than you! I kill you! Stupid monkey... my chicken is the best!";
  27. $txt3 = "Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus \"preserving keys\" may have different interpretations. Ivan's function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.";
  28. kWords($txt, 5, 4);
  29.  
  30.  
  31. ?>

Primer parámetro: el texto donde buscar; Segundo: es el número de palabras que quieres "filtrar"; Tercero: número mínimo de caracteres que debe tener la palabra.

Devuelve un array, de tipo:
Código:

Array
(
    [0] => stupid
    [1] => monkey
    [2] => chicken
    [3] => you!
    [4] => than
)


Título: Re: Algoritmo Key Words
Publicado por: [u]nsigned en 10 Agosto 2011, 23:19 pm
Muchas gracias Mad, me sera de mucha ayuda, lo implementare con una base de palabras 'poco utiles' que estoy armando con preposiciones, articulos, etc.

Saludos