Foros del Web » Programando para Internet » PHP »

para rematar mi traductor

Estas en el tema de para rematar mi traductor en el foro de PHP en Foros del Web. Hola estoy montando un codigo para que me traduzca un monton de html que tengo para no hacerlos uno a uno me traduce bien y ...
  #1 (permalink)  
Antiguo 26/06/2014, 14:37
 
Fecha de Ingreso: junio-2010
Mensajes: 19
Antigüedad: 13 años, 9 meses
Puntos: 0
para rematar mi traductor

Hola estoy montando un codigo para que me traduzca un monton de html que tengo para no hacerlos uno a uno me traduce bien y me crea los archivos traducidos en otra carpeta pero me elimina los tags html ¿como hago para que no los borre? o si ya existe algun script que haga lo que quiero seguro funciona mejor que el mio pero si no a ver si me saben orientar para que me repete los tags gracias.
  #2 (permalink)  
Antiguo 26/06/2014, 14:47
Avatar de Italico76  
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 16 años, 11 meses
Puntos: 292
Respuesta: para rematar mi traductor

No tiene nada que ver con PHP pero responderé igual:

Marca como "de solo lectura" (read only) todos los archivos que no quieras sean borrados.......
__________________
Salu2!
  #3 (permalink)  
Antiguo 26/06/2014, 14:55
 
Fecha de Ingreso: junio-2010
Mensajes: 19
Antigüedad: 13 años, 9 meses
Puntos: 0
Respuesta: para rematar mi traductor

creo que no me explique bien lo que he hecho es un script en php que me usa google transalator para traducir los textos de dentro de un idioma a otro.

me coge los html que tengo en una carperta, coge el codigo y usando el google translator como url me traduce las cadenas. de dentro del archivo.

Me genera un archivo nuevo con el mismo nombre en otro directorio con las cadenas traducidas solo que me los crea sin los tags html que hay dentro del fichero.

Disculpa si me explique mal
  #4 (permalink)  
Antiguo 26/06/2014, 15:07
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 15 años, 11 meses
Puntos: 2534
Respuesta: para rematar mi traductor

Bueno, pues ese es precisamente un problema grave: el traductor de google traduce texto, no html.

Debes ingeniar una solución, lo que se me ocurre al momento es cargar todo el documento usando la extensión de DOM, entonces iterar los nodos de texto y hacer los reemplazos uno a uno sin salirse del nodo, luego exportas como HTML de nuevo y todo debería quedar bien.

Tampoco esperes soluciones mágicas para que no tengas que hacer nada.
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #5 (permalink)  
Antiguo 26/06/2014, 15:07
Avatar de Italico76  
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 16 años, 11 meses
Puntos: 292
Respuesta: para rematar mi traductor

Si... leí mal... que pena

Coloca tu codigo aca..... asi vemos que has hecho y mirando la API vemos donde esta el error
__________________
Salu2!
  #6 (permalink)  
Antiguo 27/06/2014, 01:11
 
Fecha de Ingreso: junio-2010
Mensajes: 19
Antigüedad: 13 años, 9 meses
Puntos: 0
Respuesta: para rematar mi traductor

Esto es lo que tengo por ahora a ver si me podeis ayudar a mejorarlo gracias

no se si para mi finalidad seria mejor usar el curl la verdad que no soy muy diestro en php y en hacer esta tonteria he tardado mas de lo que se deberia acepto sugerencias, correcciones, mejoras.... (cualquier cosas que no me elimine los tags html dentro de los archivos a traducir) :D

Código PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Traductor</title>
</head>
<body>


</body>
<?php
$directorio
=opendir("./traducir"); 
while (
$archivo readdir($directorio))
{
    if (
$archivo!="." && $archivo!="..")
    {
        
$file fopen("./traducir/".$archivo"r") or exit("Unable to open file!");
        
$traducido "";
        
//Output a line of the file until the end is reached
        
while(!feof($file))
        {
            
$traducido .= traduce(fgets($file))."\r\n";
        }
        
fclose($file);
        
$nuevoarchivo fopen("./traducido/".$archivo"w+");
        
fwrite($nuevoarchivo,$traducido);
        
fclose($nuevoarchivo);
    }
}
closedir($directorio); 
//Procesa Google Translate
function traductor($url)
{
    
//Procesamos la URL
    
$contenido file_get_contents($url);
    
//Procesamos la respuesta
    
$contenido preg_replace('/,,,|,,/'',"0",'$contenido);
    
$contenido json_decode($contenido);
 
    return 
trim($contenido[0][0][0]);
}
//Traduce las descripciones a otros idiomas
function traduce($descripcion)
{
    
//Codificamos la descripción para que Google la entienda
    
$descripcion urlencode($descripcion);
    
//Traducimos
    
$url "https://translate.google.es/translate_a/single?client=t&sl=ru&tl=en&hl=es&dt=bd&dt=ex&dt=ld&dt=md&dt=qc&dt=rw&dt=rm&dt=ss&dt=t&dt=at&dt=sw&ie=UTF-8&oe=UTF-8&oc=1&otf=1&trs=1&inputm=1&srcrom=1&ssel=0&tsel=0&q=".$descripcion;
    
$traduccion traductor($url);
    return 
$traduccion;
}
?>
</html>

Última edición por Sirrion; 27/06/2014 a las 02:05
  #7 (permalink)  
Antiguo 28/06/2014, 08:30
 
Fecha de Ingreso: junio-2010
Mensajes: 19
Antigüedad: 13 años, 9 meses
Puntos: 0
Respuesta: para rematar mi traductor

alguna idea al respecto? :(
  #8 (permalink)  
Antiguo 28/06/2014, 11:30
Avatar de Durgeoble  
Fecha de Ingreso: marzo-2003
Mensajes: 462
Antigüedad: 21 años
Puntos: 2
Respuesta: para rematar mi traductor

separa el contenido de la vista y traduce el contenido, es lo único que se me ocurre
__________________
Todas mis respuestas funcionaran correctamente en aquellos navegadores que respeten los estandares.
  #9 (permalink)  
Antiguo 28/06/2014, 12:26
Avatar de Italico76  
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 16 años, 11 meses
Puntos: 292
Respuesta: para rematar mi traductor

Ya me acorde de una solucion "general"......... la hice en el 2008

Me hizo acordar esto:

Cita:
Iniciado por Durgeoble Ver Mensaje
separa el contenido de la vista y traduce el contenido, es lo único que se me ocurre

Cita:
<i>vamos a probar</i> una vieja idea de <b><i>@Italico76</i></b> a ver si logro <b>traducir</b> esto sin perder tags <b>en el camino</b> !!!
lo deja como:

Cita:
<i>we will try</i>an old idea<b><i> @Italico76</i></b> to see if I <b>translate</b> this without losing tags <b> on the road</b>!
Código PHP:
Ver original
  1. <?php
  2. <?php
  3. include 'html_editor.class.php';
  4.  
  5. /*
  6.     Ejemplo de uso de la clase html_editor para traducir un texto sin perder los tags usando
  7.     la API de Google Translate
  8. */
  9.  
  10.  
  11. $html = '<i>vamos a probar</i> una vieja idea de <b><i>@Italico76</i></b> a ver si logro <b>traducir</b> esto sin perder tags <b>en el camino</b> !!!   ';
  12.  
  13. $texto = new htmlEditor($html);
  14.  
  15.  
  16. function fill_right($str)
  17. {
  18.     if (empty($str))
  19.         return $str;
  20.    
  21.     return $str[strlen($str)-1]==' ' ? $str : $str.' ';
  22. }
  23.  
  24. ///Procesa Google Translate
  25. function traductor($url)
  26. {
  27.     //Procesamos la URL
  28.     $contenido = explode('"',str_replace('[[["','',file_get_contents($url)));  
  29.  
  30.     $contenido = str_replace(',,','',$contenido);
  31.     $contenido = str_replace('[','',$contenido);
  32.    
  33.     return $contenido[0];
  34. }
  35.  
  36. // aca iria TU funcion traduce
  37. function traduce($descripcion,$sl = 'es',$tl= 'en',$hl= 'it')
  38. {  
  39.     //Codificamos la descripción para que Google la entienda
  40.     $descripcion = urlencode($descripcion);
  41.     //Traducimos
  42.     $url = "https://translate.google.es/translate_a/single?client=t&sl=$sl&tl=$tl&hl=$hl&dt=bd&dt=ex&dt=ld&dt=md&dt=qc&dt=rw&dt=rm&dt=ss&dt=t&dt=at&dt=sw&ie=UTF-8&oe=UTF-8&oc=1&otf=1&trs=1&inputm=1&srcrom=1&ssel=0&tsel=0&q=".$descripcion;
  43.     $traduccion = traductor($url);
  44.    
  45.     return $traduccion;
  46. }
  47. foreach ($texto as $fragemento)
  48. {
  49.     $translated = traduce($fragemento);    
  50.     $texto->setChunk(fill_right($translated));
  51. }
  52.  
  53.  
  54.        
  55. // HTML traducido  
  56. echo $texto;


y mi libreria de 2008 actualizada


Código PHP:
Ver original
  1. <?php
  2. /*
  3.     HTML EDITOR
  4.     @author: Pablo Bozzolo (2008)
  5.     minor update 2013
  6.    
  7.    
  8.     Recibe un HTML y permite modificar el texto sin preocuparse de alterar los tags
  9.  
  10.     __construct(html)  recibe el html
  11.     count()  devuelve el numero de trozos de texto desnudos
  12.     setChunk(fragmento,n) cambia esa frase (elemento del array en la clase)
  13.     getChunk(n) devuelve el fragmento (bit) que se pide
  14.     getHTML() reconstruye el HTML uniendo las "frases" (texto puro) con los tags y lo devuelve.
  15.    
  16.     Implementa Iterator asi que getChunk() y setChunk() no requieren de un (n)
  17. */
  18. class htmlEditor implements Countable, Iterator
  19. {  
  20.  
  21.     private $_html;
  22.     private $_tag;   // tags
  23.     private $_notag; // texto puro
  24.     private $_notagCant;
  25.     private $_quitarEspacio;
  26.  
  27.     function __construct($html = NULL)
  28.     {
  29.         if (!is_null($html))
  30.             $this->setHtml($html);
  31.     }  
  32.  
  33.     function count()
  34.     {
  35.         return $this->_notagCant;
  36.     }
  37.  
  38.     function setHtml($html)
  39.     {
  40.         $this->_html = $html;
  41.        
  42.         if ((strlen($this->_html)>0) and ($this->_html[0]=='<')){
  43.             $this->_html = ' '.$this->_html;
  44.             $this->_quitarEspacio=TRUE;  
  45.         }  
  46.  
  47.         $this->no_tags();      
  48.         $this->_notagCant = count ($this->_notag);
  49.     }
  50.  
  51.     function getHtml()
  52.     {      
  53.         $html = null;
  54.        
  55.         for ($i=0;$i<$this->count()-1;$i++)
  56.         {    
  57.             $a = $this->_notag[$i];
  58.             $b = $this->_tag[$i];
  59.             $html = $html.$a.$b;  
  60.         }
  61.    
  62.         $html .= $this->_notag[$i];
  63.    
  64.         //if ($this->_quitarEspacio)
  65.         //  $html =substr ($html,0,strlen($html)-1);
  66.                
  67.         return $html;
  68.     }
  69.  
  70.     function setChunk($element,$n=NULL)
  71.     {
  72.         if (is_null($n))
  73.             $n = $this->key();
  74.        
  75.         $this->_notag[$n]=$element;
  76.     }    
  77.  
  78.     function getChunk($n)
  79.     {
  80.         return $this->_notag[$n];
  81.     }
  82.  
  83.   /*
  84.      pre-condicion para $this->_tag : la cadena debe empezar con algo distinto a un tag (<)
  85.   */
  86.     private function no_tags()
  87.     {    
  88.    
  89.         preg_match_all('@(<[/]?[a-z]{1,}[^>]{0,}[/]?[\w]{0,}?>)@is', $this->_html, $matches);
  90.         $full_tags = $matches[0];
  91.    
  92.         $full_tags = array_reverse($full_tags); // tengo que sacar del principio
  93.         $cant = count($full_tags);
  94.  
  95.         $ini = 0;
  96.        
  97.         for ($i=1;$i<=$cant+1;$i++)
  98.         {
  99.             $ti = array_pop ($full_tags);  
  100.             $fin= strpos($this->_html, $ti,$ini);  
  101.            
  102.             if ($fin==NULL)
  103.                 $fin=strlen($this->_html);
  104.    
  105.             $dif    = ($fin-$ini);    
  106.             $inserto= substr ($this->_html,$ini,$dif);  
  107.             $this->_notag[] = $inserto;            
  108.             $ini    = $fin +strlen ($ti);  
  109.         }  
  110.  
  111.         $this->_tag = $matches[0];  
  112.     }  
  113.  
  114.     /* Iterator */
  115.     function rewind() {        
  116.         reset($this->_notag);
  117.     }
  118.  
  119.     public function current()
  120.     {
  121.         return current($this->_notag);
  122.     }
  123.  
  124.     public function key()
  125.     {        
  126.         return key($this->_notag);
  127.     }
  128.  
  129.     public function next()
  130.     {
  131.         next($this->_notag);        
  132.     }
  133.  
  134.     public function valid()
  135.     {  
  136.         return isset($this->_notag[$this->key()]);
  137.     }
  138.  
  139.    
  140.     public function __toString()
  141.     {      
  142.         return $this->  getHtml();     
  143.     }
  144.  
  145. }


Mi clase fue posteada en 2008 y profundamente olvidada... de hecho el post de aporte.. SE PERDIO!!!

Pero proponia un uso similar a este en 2009


HOY... lo haria MUCHO MAS SIMPLE con replace_callback() y la expresion correcta que recoja el texto fuera de los tags... esa clase es innecesaria si lo puedes hacer asi en 1 o 2 lineas de codigo
__________________
Salu2!

Última edición por Italico76; 28/06/2014 a las 18:04
  #10 (permalink)  
Antiguo 30/06/2014, 15:29
 
Fecha de Ingreso: junio-2010
Mensajes: 19
Antigüedad: 13 años, 9 meses
Puntos: 0
Respuesta: para rematar mi traductor

Perdon la demora, gracias por el aporte no he podido estar hasta hoy en el pc.

He queria adaptarlo para que me traduzca varios html que deje dentro de una carpeta pero solo me coge de esa carpeta 1 html los demas no me los coge son muchos html los que he de traducir y de 1 en 1 es un poco engorroso si al menos me coge de 5 en 5 o 10 en 10 de esa carpeta ya seria mas rapido. Dejo lo que he hecho a ver si alguien sabe el porque no me los coge. Gracias

Código PHP:
<?php
/*
    HTML EDITOR
    @author: Pablo Bozzolo (2008)
    minor update 2013
    
    
    Recibe un HTML y permite modificar el texto sin preocuparse de alterar los tags
 
    __construct(html)  recibe el html
    count()  devuelve el numero de trozos de texto desnudos
    setChunk(fragmento,n) cambia esa frase (elemento del array en la clase)
    getChunk(n) devuelve el fragmento (bit) que se pide 
    getHTML() reconstruye el HTML uniendo las "frases" (texto puro) con los tags y lo devuelve.
    
    Implementa Iterator asi que getChunk() y setChunk() no requieren de un (n)
*/
class htmlEditor implements CountableIterator
{  
 
    private 
$_html;
    private 
$_tag;   // tags
    
private $_notag// texto puro
    
private $_notagCant;
    private 
$_quitarEspacio;
 
    function 
__construct($html NULL)
    {
        if (!
is_null($html))
            
$this->setHtml($html);
    }  
  
    function 
count()
    { 
        return 
$this->_notagCant;
    }
  
    function 
setHtml($html)
    {
        
$this->_html $html;
        
        if ((
strlen($this->_html)>0) and ($this->_html[0]=='<')){
            
$this->_html ' '.$this->_html
            
$this->_quitarEspacio=TRUE;  
        }  
 
        
$this->no_tags();       
        
$this->_notagCant count ($this->_notag);
    }
  
    function 
getHtml()
    {       
        
$html null;
        
        for (
$i=0;$i<$this->count()-1;$i++)
        {     
            
$a $this->_notag[$i];
            
$b $this->_tag[$i];
            
$html $html.$a.$b;  
        }
    
        
$html .= $this->_notag[$i];
    
        
//if ($this->_quitarEspacio)
        //  $html =substr ($html,0,strlen($html)-1); 
                
        
return $html;
    }
 
    function 
setChunk($element,$n=NULL)
    {
        if (
is_null($n))
            
$n $this->key();
        
        
$this->_notag[$n]=$element;
    }    
  
    function 
getChunk($n)
    {
        return 
$this->_notag[$n];
    }
  
  
/*
     pre-condicion para $this->_tag : la cadena debe empezar con algo distinto a un tag (<)
  */
    
private function no_tags()
    {    
    
        
preg_match_all('@(<[/]?[a-z]{1,}[^>]{0,}[/]?[\w]{0,}?>)@is'$this->_html$matches);
        
$full_tags $matches[0];
   
        
$full_tags array_reverse($full_tags); // tengo que sacar del principio
        
$cant count($full_tags);
 
        
$ini 0
        
        for (
$i=1;$i<=$cant+1;$i++)
        {
            
$ti array_pop ($full_tags);  
            
$finstrpos($this->_html$ti,$ini);  
            
            if (
$fin==NULL)
                
$fin=strlen($this->_html);
    
            
$dif    = ($fin-$ini);     
            
$insertosubstr ($this->_html,$ini,$dif);  
            
$this->_notag[] = $inserto;            
            
$ini    $fin +strlen ($ti);  
        }  
 
        
$this->_tag $matches[0];  
    }  
  
    
/* Iterator */
    
function rewind() {        
        
reset($this->_notag);
    }
 
    public function 
current()
    {
        return 
current($this->_notag);
    }
 
    public function 
key()
    {        
        return 
key($this->_notag);
    }
 
    public function 
next()
    {
        
next($this->_notag);        
    }
 
    public function 
valid()
    {   
        return isset(
$this->_notag[$this->key()]);
    }
 
    
    public function 
__toString()
    {       
        return 
$this->  getHtml();      
    }
  
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Traductor</title>
</head>
<body>


</body>
<?php
$directorio
=opendir("./traducir"); 
while (
$archivo readdir($directorio))
{
    if (
$archivo!="." && $archivo!="..")
    {
        
$file fopen("./traducir/".$archivo"r") or exit("Unable to open file!");
        
$texto = new htmlEditor(fread($file,filesize("./traducir/".$archivo)));
        
$traducido "";
        foreach (
$texto as $fragemento)
        {
            
$traducido traduce($fragemento,"ru","en","es");     
            
$texto->setChunk(fill_right($traducido));
        }
        
fclose($file);
        
$nuevoarchivo fopen("./traducido/".$archivo"w+");
        
fwrite($nuevoarchivo,$texto);
        
fclose($nuevoarchivo);
    }
}
closedir($directorio);  
 
function 
fill_right($str)
{
    if (empty(
$str))
        return 
$str;
    
    return 
$str[strlen($str)-1]==' ' $str $str.' ';
}
 
///Procesa Google Translate
function traductor($url)
{
    
//Procesamos la URL
    
$contenido explode('"',str_replace('[[["','',file_get_contents($url)));   
 
    
$contenido str_replace(',,','',$contenido);
    
$contenido str_replace('[','',$contenido);
    
    return 
$contenido[0];
}
 
// aca iria TU funcion traduce
function traduce($descripcion,$sl 'es',$tl'en',$hl'it')
{   
    
//Codificamos la descripción para que Google la entienda
    
$descripcion urlencode($descripcion);
    
//Traducimos
    
$url "https://translate.google.es/translate_a/single?client=t&sl=$sl&tl=$tl&hl=$hl&dt=bd&dt=ex&dt=ld&dt=md&dt=qc&dt=rw&dt=rm&dt=ss&dt=t&dt=at&dt=sw&ie=UTF-8&oe=UTF-8&oc=1&otf=1&trs=1&inputm=1&srcrom=1&ssel=0&tsel=0&q=".$descripcion;
    
$traduccion traductor($url);
    
    return 
$traduccion;
}
?>
</html>
  #11 (permalink)  
Antiguo 04/07/2014, 08:24
 
Fecha de Ingreso: junio-2010
Mensajes: 19
Antigüedad: 13 años, 9 meses
Puntos: 0
Respuesta: para rematar mi traductor

alguna sugerencia de que tengo mal? gracias

Etiquetas: html, traductor
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 05:18.