• Publicidad

Problemas con columnas

¿Apenas comienzas con Perl? En este foro podrás encontrar y hacer preguntas básicas de Perl con respuestas aptas a tu nivel.

Problemas con columnas

Notapor lis » 2008-11-22 22:05 @961

Hola. En una ocasión anterior me ayudaron a descargar archivos HTML y transformarlos a .txt, acá está el script:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
#!/usr/bin/perl

use strict;
use LWP::Simple;
$|++;

my $URL = 'http://weather.uwyo.edu/cgi-bin/sounding?region=samer&TYPE=TEXT%3ALIST&YEAR=2005';
my $url = '&STNM=85442';

foreach my $mes ( "04" ) {
foreach my $dia ( "01" .. "09" ) {
foreach my $hora ( 12 ) {

my $fecha   = "$dia-$mes-$hora";
my $fichero = "$fecha.dat";
my $pagina = get("$URL&MONTH=$mes&FROM=$dia$hora&TO=$dia$hora$url");

if (defined $pagina) {
if ((my $datos) = $pagina =~ m/^<pre>(.+?)^<\/pre>$/simo) {
$datos =~ s{<.+?>}{}g;
open  (FICHERO, ">$fichero");
print FICHERO "$datos\n";
close (FICHERO);
}}}}}
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4


El problema que tengo ahora es que no puedo trabajar las columnas independientemente, es decir, si quiero extraer una columna y copiarla en un nuevo archivo, lo que hace es mezclar, sobre todo al final, parte de otra columna a esta.

Mi pregunta es si hay alguna función que me permita trabajar las columnas individualmente, y claro, sin mezclarse.

Nuevamente muchas gracias por su valiosa ayuda.
lis
Perlero nuevo
Perlero nuevo
 
Mensajes: 106
Registrado: 2008-05-27 21:43 @946

Publicidad

Notapor explorer » 2008-11-23 06:06 @296

No hay funciones primitivas en Perl para manejar columnas.

Puedes empezar por dividir las líneas con el comando split() y guardar los valores de cada columna en un array o en un array bidimensional.

A nivel de módulos puedes usar Data::Tabular o File::Tabular, pero antes debes limpiar o extraer la parte de las columnas que deseas manipular, por lo que volvemos al split().

En estos foros hay muchos ejemplos de eso, como es el caso de las columnas con ángulos que tu mismo pusiste ayer.

Estaría bien saber a qué te refieres con "mezclarse". Si viste el último ejemplo que te puse en el caso de los ángulos, fíjate que la salida está formateada con printf().

Actualización: si te refieres a la tabla de datos que aparece en la página web, no puedes usar el comando split(), porque hay filas a las que le faltan columnas (están en blanco). Debes usar el comando unpack() para extraerlas, indicando las posiciones fijas en las que se encuentran.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Notapor lis » 2008-11-23 11:21 @515

Hola Explorer: el script que está en un principio, me descarga de esta forma:
Código: Seleccionar todo
-----------------------------------------------------------------------------
   PRES   HGHT   TEMP   DWPT   RELH   MIXR   DRCT   SKNT   THTA   THTE   THTV
    hPa     m      C      C      %    g/kg    deg   knot     K      K      K
-----------------------------------------------------------------------------
 1002.0    137   16.8   14.6     87  10.53    210      7  289.8  319.6  291.6
 1000.0    128   16.2   11.2     72   8.42    205      7  289.4  313.3  290.8
  925.0    785   12.2    7.9     75   7.27    215      5  291.8  312.8  293.1
  884.0   1163    9.2    6.6     84   6.96     96      8  292.5  312.7  293.7
  882.0   1182    9.2    5.4     77   6.41     90      8  292.7  311.4  293.8
  877.0   1230   13.3    1.3     44   4.81     75      8  297.4  311.9  298.3
  874.0   1259   15.8   -1.2     31   4.03     70      8  300.3  312.7  301.0
  853.0   1465   16.4   -1.6     29   4.01     35     12  303.0  315.5  303.7
  850.0   1495   16.4   -1.6     29   4.02     30     12  303.3  315.9  304.1
  843.0   1565   16.2   -2.6     27   3.75     20     13  303.8  315.6  304.5
  838.0   1615   16.1   -3.4     26   3.56     20     12  304.2  315.4  304.9
  787.0   2147   14.6  -11.4     15   2.04    355      8  308.1  314.9  308.5
  733.0   2743   10.6   -8.4     25   2.78    359      2  310.1  319.2  310.6
  711.0   2996    9.0  -14.6     17   1.74      0      0  311.0  316.9  311.4
  700.0   3125    8.2  -17.8     14   1.36    335      3  311.5  316.2  311.8
  685.0   3304    7.7  -30.7      5   0.44    315      9  312.9  314.5  313.0
  683.0   3328    7.6  -32.4      4   0.37    316      9  313.1  314.4  313.1
  680.0   3364    8.0  -32.5      4   0.37    317     10  313.9  315.3  314.0
  652.0   3705    5.1  -32.9      4   0.37    330     16  314.4  315.8  314.5
  644.0   3805    4.3  -33.1      5   0.37    315     16  314.6  316.0  314.7
  603.0   4338   -0.2  -33.8      6   0.37    310     16  315.4  316.8  315.4
  597.0   4420   -0.9  -33.9      6   0.37    301     16  315.5  316.9  315.6
  590.0   4514   -0.6  -35.3      5   0.32    290     17  316.9  318.1  317.0
  588.0   4541   -0.5  -35.7      5   0.31    290     17  317.3  318.5  317.4
  541.0   5198   -4.0  -45.8      2   0.12    300     24  320.8  321.3  320.8
  502.0   5789   -7.1  -54.8      1   0.04    275     29  323.9  324.1  323.9
  500.0   5820   -7.3  -55.3      1   0.04    275     29  324.1  324.3  324.1
  469.0   6314   -9.9  -57.2      1   0.04    290     36  326.8  326.9  326.8
  458.0   6497  -10.9  -57.9      1   0.03    289     37  327.8  327.9  327.8
  400.0   7520  -18.7  -62.7      1   0.02    285     45  330.6  330.7  330.6
  396.0   7595  -19.3  -63.3      1   0.02    285     46  330.8  330.9  330.8
  369.0   8119  -20.9  -63.9      1   0.02    281     56  335.4  335.5  335.4
  362.0   8258  -22.2  -62.1      1   0.02    280     59  335.5  335.6  335.5
  324.0   9065  -29.7  -51.7     10   0.10    283     62  335.9  336.4  335.9
  300.0   9610  -33.5  -67.5      2   0.01    285     64  338.0  338.1  338.1
  286.0   9942  -36.3  -69.3      2   0.01    286     66  338.7  338.7  338.7
  250.0  10860  -42.5  -71.5      3   0.01    290     72  342.7  342.8  342.8
  238.0  11191  -44.4  -76.8      2   0.00    290     76  344.7  344.8  344.7
  229.0  11451  -45.9  -80.9      1   0.00    291     76  346.3  346.3  346.3
  200.0  12340  -53.9  -76.9      4   0.01    295     76  347.2  347.3  347.2
  177.0  13096  -60.5  -80.1      6   0.00    300     77  348.7  348.7  348.7
  157.0  13838  -67.0  -83.3      8   0.00    295     79  349.8  349.9  349.8
  150.0  14120  -69.5  -84.5     10   0.00    290     74  350.2  350.2  350.2
  127.0  15099  -73.9  -86.3     13   0.00    290     61  359.3  359.3  359.3
  125.0  15193  -74.3  -86.5     14   0.00    289     60  360.2  360.2  360.2
  106.0  16144  -77.1  -88.3     16   0.00    275     49  372.3  372.3  372.3
  100.0  16480  -75.3  -88.9     11   0.00    265     39  382.0  382.0  382.0
   97.0  16657  -74.8  -89.2      9   0.00    275     28  386.4  386.4  386.4
   95.5  16748  -74.5  -89.4      9   0.00    281     30  388.6  388.6  388.6
   90.0  17090  -76.4  -90.0     10   0.00    305     36  391.4  391.4  391.4
   85.0  17419  -78.3  -90.7     12   0.00    305     46  394.1  394.1  394.1
   83.4  17529  -78.9  -90.9     13   0.00    300     48  395.0  395.0  395.0
   83.0  17557  -78.8  -90.9     13   0.00    300     48  395.8  395.8  395.8
   73.0  18298  -75.2  -92.3      6   0.00    235     24  418.0  418.0  418.0
   71.0  18458  -74.5  -92.6      5   0.00    195     17  423.0  423.0  423.0
   70.0  18540  -74.1  -92.8      4   0.00    195     16  425.5  425.5  425.5
   68.0  18708  -74.2  -93.1      4   0.00    195     12  428.8  428.8  428.8
   67.0  18794  -74.3  -93.2      4   0.00    215      9  430.5  430.5  430.5
   66.6  18829  -74.3  -93.3      4   0.00    212      9  431.2  431.2  431.2
   63.0  19159  -71.2  -93.9      2   0.00    180     10  445.0  445.0  445.0
   61.0  19350  -69.3  -94.2      2   0.00    155     14  453.2  453.2  453.2
   57.4  19710  -65.9  -94.9      1   0.00     95      9  468.9  468.9  468.9
   56.0  19859  -67.0  -96.0      1   0.00     70      7  469.8  469.8  469.8
   55.0  19967  -67.8  -96.8      1   0.00     75      5  470.4  470.4  470.4
   54.6  20011  -68.1  -97.1      1   0.00     85      7  470.6  470.6  470.6
   53.0  20190  -67.6  -96.6      1   0.00    125     14  475.7  475.7  475.7
   50.0  20540  -66.7  -95.7      1   0.00    110     18  485.9  485.9  485.9
   49.0  20665  -66.2  -95.4      1   0.00    105     16  489.9  489.9  489.9
   47.0  20923  -65.2  -94.7      1   0.00    110     13  498.3  498.3  498.3
   46.0  21056  -64.6  -94.3      1   0.00    135     18  502.6  502.6  502.6
   44.0  21331  -63.5  -93.6      1   0.00    110     29  511.8  511.8  511.8
   41.0  21768  -61.7  -92.4      1   0.00     95     32  526.6  526.6  526.6
   39.0  22077  -60.5  -91.6      1   0.00     80     30  537.4  537.4  537.4
   37.0  22403  -59.1  -90.7      1   0.00     90     22  548.9  548.9  548.9
   35.2  22712  -57.9  -89.9      1   0.00     54     20  560.0  560.1  560.0
   35.0  22748  -57.8                          50     20  561.3         561.3
   33.0  23123  -56.5                          70     13  574.3         574.3
   30.0  23730  -54.3                          90     20  596.0         596.0
   28.0  24175  -52.6                          80     17  612.7         612.7
   26.0  24653  -50.7                         105     27  631.1         631.1
   25.0  24907  -51.2                          90     29  636.7         636.7
   24.0  25172  -51.8                          75     27  642.5         642.5
   23.8  25226  -51.9                          78     25  643.8         643.8
   23.0  25449  -51.2                          90     18  652.2         652.2
   20.1  26327  -48.3                          76     25  686.6         686.6
   20.0  26360  -48.3                          75     25  687.6         687.6
   19.0  26700  -47.5                          90     24  700.1         700.1
   18.0  27058  -46.7                          75     23  713.6         713.6
   16.2  27757  -45.1                          88     29  740.6         740.6
   16.0                                        90     30                     
Station information and sounding indices
                         Station identifier: SCFA
                             Station number: 85442
                           Observation time: 050401/1200
                           Station latitude: -23.43
                          Station longitude: -70.45
                          Station elevation: 137.0
                            Showalter index: 11.52
                               Lifted index: 12.77
    LIFT computed using virtual temperature: 12.54
                                SWEAT index: 53.01
                                    K index: -3.90
                         Cross totals index: 5.70
                      Vertical totals index: 23.70
                        Totals totals index: 29.40
      Convective Available Potential Energy: 0.00
             CAPE using virtual temperature: 0.00
                      Convective Inhibition: 0.00
             CINS using virtual temperature: 0.00
                     Bulk Richardson Number: 0.00
          Bulk Richardson Number using CAPV: 0.00
  Temp [K] of the Lifted Condensation Level: 282.56
Pres [hPa] of the Lifted Condensation Level: 910.02
     Mean mixed layer potential temperature: 290.31
              Mean mixed layer mixing ratio: 8.22
              1000 hPa to 500 hPa thickness: 5692.00
Precipitable water [mm] for entire sounding: 15.37



En donde yo manualmente borro lo que no me sirve y solo dejo las once columnas con datos y como tu bien dices, hay filas que le faltan columnas, y hago el siguiente script usando unpack() para ver si las columnas las puedo trabajar independientemente (es un script que encontré en el foro):

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
#!/usr/bin/perl

open FL, "01-04-12.dat"; Donde ocupo un solo archivo para probar.
my @lines = <FL>;
my $aline;
my $a = 0;
close FL;
foreach(0 .. $#lines) {$aline = "$aline$lines[$a++]";}
my $palabras = unpack("b*", $aline);
print "$palabras\n";
my $all = pack("b*", $palabras);
open QT, "+>01-04-12.txt";
print QT "$all";
close QT;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


Y una vez que obtengo el resultado, ocupo el script de los ángulos :

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
#!/usr/bin/perl
use strict;
use warnings;

my @ficheros = glob "*.txt";
foreach my $fichero ( @ficheros ) {
 
my $fecha = substr($fichero,0,5);

open (DATOS, "<$fichero");
open (ARCHIVO, ">$fecha.txt");

while (<DATOS>) {

my ($ang, $hip) = (split)[6,7];

$ang *= 3.141592654/180;

printf ARCHIVO "%5.2f %5.2f\n", $hip * cos $ang, $hip * sin $ang;
}
}
close (DATOS);
close (ARCHIVO);
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


Y el archivo resultante me hace bien la operación hasta la línea 75 y de ahí en adelante hasta la línea 90 que es donde hay dato me da como resultado cero, y a eso me refiero cuando se mezclan las columnas ya que me imagino que toma las de al lado donde no hay datos y es por eso el resultado 0.

Por favor, me puedes revisar el script donde ocupo unpack(), muchísimas gracias.
lis
Perlero nuevo
Perlero nuevo
 
Mensajes: 106
Registrado: 2008-05-27 21:43 @946

Notapor explorer » 2008-11-23 13:25 @601

¿Obtención desde el web... edición "manual"... y otra operación de cálculo...?

¿Dos scripts y una edición "manual"?

¿No es mejor hacerlo todo junto?
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
#!/usr/bin/perl
use strict;
use warnings;

use LWP::Simple;

my $URL     = 'http://weather.uwyo.edu/cgi-bin/sounding?region=samer&TYPE=TEXT%3ALIST&YEAR=2005&STNM=85442';
my $GRD2RAD = 3.141592654 / 180;

for my $mes  ( "04"         ) {
for my $dia  ( "01" .. "09" ) {
for my $hora (  12          ) {

    my $fecha   = "$dia-$mes-$hora";
    my $pagina  = get("$URL&MONTH=$mes&FROM=$dia$hora&TO=$dia$hora");

    if (defined $pagina) {
        if ((my $datos) = $pagina =~ m/^<PRE>(.+?)<\/PRE>/sim) {

            open FICHERO, ">$fecha.txt" or warn "ERROR: No puedo escribir en $fecha.txt: $!\n" and next;

            for my $linea (split "\n", $datos) {
                next if $linea !~ /^\s*\d/;         # Nos quedamos solo con los datos de la tabla

                my $grados = $GRD2RAD * substr $linea, 43, 8;
                my $nudos  = 0        + substr $linea, 51, 6;

                printf FICHERO "%6.2f %6.2f\n",
                              $nudos * cos $grados,
                              $nudos * sin $grados;
            }

            close FICHERO;
        }
        else {
            warn "ERROR: No encuentro datos en la página de $fecha\n";
        }
    }
    else {
        warn "ERROR: No se pudo recuperar los datos de $fecha\n";
    }
}}}
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


De verdad, lis... tienes que ponerte en serio con Perl... te ahorrarás mucho tiempo... :wink:
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Notapor lis » 2008-11-23 15:49 @701

¡¡MUCHAS GRACIAS, EXPLORER!!
lis
Perlero nuevo
Perlero nuevo
 
Mensajes: 106
Registrado: 2008-05-27 21:43 @946


Volver a Básico

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 3 invitados

cron