Buscar texto en un fichero

Buscar texto en un fichero

Postby antolin » Wed Nov 24, 2010 11:26 am

Hola amigos foreros.

Me ha tocado lidiar con ficheros de texto muy grandes (muchos megas). Tengo que encontrar ciertos patrones de texto para procesar lo que va detrás.

Mi intención es utilizar las funciones de manejo de ficheros de bajo nivel, tipo FOPEN(), FREAD(), etc.. Pero ¿que hago para la búsqueda?

Mi pregunta es, hay alguna forma de encontrar patrones de texto en dichos ficheros sin tener que cargarlos en variables para buscar con AT(). Algunos ficheros miden mas de 15 megas. ¿Existe alguna función de búsqueda de bajo nivel tipo FSCAN() o algo así en xHarbour?

Gracias de antemano.
Peaaaaaso de foro...
antolin
 
Posts: 494
Joined: Thu May 10, 2007 8:30 pm
Location: Sevilla

Re: Buscar texto en un fichero

Postby noe aburto » Wed Nov 24, 2010 3:24 pm

Saludos.

En efecto, con las funciones fopen(), fread(), freadstr() puedes leer el archivo binario que quieras y del tamaño que sea.
Sin son archivos texto que tengan internamente un delimitador con un "pipe", un CRLF o el que sea, utiliza la freadstr() que te permite leer cadenas de la misma longitud. p.ej.

funtion miarchivo()
local n,txt,bloque:=256 // numero de caracteres que tenga la cadena txt hasta 65,000 aprox.

n:=fopen('archivo',MODO) // modo es segun la apertura de lectura, escritura....
while !empty(txt:=freadstr(n,bloque))
... aqui puedo ver el contenido de txt
end
return NIL

puedes incluso crear varios archivos txt1,txt2,txt.... usando fwrite() con otro archivo creado

Fwh 8.11, xH1.1, bcc55
Noé Aburto Sánchez
Tec. Prog. de Sistemas. -Morelia, Mich. México.
fwh 20.06, Harbour 3.2.0, bcc 7.4
TsBrowse 9.0, TsButton 7.0, xEdit 6.1
naburtos@gmail.com, noeaburto67@hotmail.com
User avatar
noe aburto
 
Posts: 418
Joined: Wed Nov 26, 2008 6:33 pm
Location: Morelia, Mich. Mexico.

Re: Buscar texto en un fichero

Postby JmGarcia » Wed Nov 24, 2010 8:41 pm

Las famosas librerías FUNCKY tenían una función llamada flocate que era estupenda.

La última versión 6 NO la tiene.

Su descripción:
Name:
flocate() - locate text in a text file
_xkey() - specify no abort in flocate()
_xkeyval() - specify key that aborts flocate()

Usage:
[<integer>] = flocate(<handle>,<string>,[<case>])
[<logical>] = _xkey([<logical>])
[<key>] = _xkeyval(<key>)

Params:
integer <handle> from a previous fopen() or fcreate()
string <string> - the string to locate in the file
logical <case> - optional case specifier. If <case>
is .T., then the text of the file is converted to uppercase
before it is compared to <string>, If <case> is false,
then the text is converted to lowercase before it is
compared to <string>. If this parameter is left off,
then the text is left as is. To search for non case
sensitive text, use the appropriate <case> value, and
then convert the string to be searched for to either upper
or lower case. Note that converting the text in the file
to either upper or lower case does not modify the text in
the file.

_xkey() tells flocate() if the user is allowed to abort
an flocate() search via an ESCape key. _xkeyval() tells
flocate() what the ESCape key is. The default value for
_xkey() is always .T. (aborting allowed). the default
abort key is ESCape (27) until you redefine it._xkey()
parameters are logical .T. to turn user abort on, .F.
to turn it off. _xkeyval() parameters are any valid
inkey() value that you want the abort key to be. The
default is to have abort capability on using ESCape.

Returns:
integer equal to the offset of the first byte of the
found string. The file pointer is positioned on the
first letter of the found string. if a read error occurs
flocate() returns a -1. If the string is not found, a -2
is returned and the pointer is returned to the position where
it started the search. If the user aborted the search, a
-3 is returned and the pointer is returned to the position
where it started the search.

If no parameters are sent to _xkey() it returns the
current state of the _xkey() flag - .T. equals on, .F.
equals off. _xkeyval() returns the current abort key
value as an integer.

---------------------------------------- Example --------------------
Code: Select all  Expand view

                 use names
                 handle = fopen("names.txt")
                 offset = flocate(handle,"dLESKO")
                 if offset < 0
                      ? "text not found...."
                 else
                      m_name = freadline(handle)
                      m_address = freadline(handle)
                      m_city = freadline(handle)
                      m_state = freadline(handle)
                      m_zip = freadline(handle)
                      replace name with m_name,;
                             address with m_address,;
                             city with m_city,;
                             state with m_state,;
                             zip with m_zip
                 endif

                 fclose(handle)
                 close databases


Note: Searching takes a about 1 second per 50k of file depending
on type of machine used. If a no find occurs, (-2 or -3)
the file pointer is left where it started. If a read
error occurs (-1), then the file pointer can be anywhere.
flocate() starts the search starting at the current
pointer position and stops at the first occurrence of
the found string. To search for multiple occurrences, find
the first occurrence, freadstr() or fseek() past it, and
start searching for the next occurrence.
Mi abuelo decía: Los aviones vuelan porque Dios quiere, y los helicópteros ni Dios sabe porque vuelan.
FWH 16.02, xHarbour 1.2.3, Harbour 3.2.0, WorkShop 4.5, AJ Make 0.30, Borlan BCC 7.00, VisualStudio 2013
User avatar
JmGarcia
 
Posts: 654
Joined: Mon May 29, 2006 3:14 pm
Location: Madrid - ESPAÑA

Re: Buscar texto en un fichero

Postby Daniel Garcia-Gil » Wed Nov 24, 2010 9:17 pm

Saludos


Puedes mirar la clase TFile de fivewin
User avatar
Daniel Garcia-Gil
 
Posts: 2365
Joined: Wed Nov 02, 2005 11:46 pm
Location: Isla de Margarita

Re: Buscar texto en un fichero

Postby JmGarcia » Wed Nov 24, 2010 9:59 pm

JmGarcia wrote:La última versión 6 NO la tiene.


Me adelante a pensar que no la tenía... pues la tiene a traves de COM (common object model).

Locate
Locate a string of text in the file
--------------------------------------------------------------------------------
FUNCky 6.0®
COM Component
--------------------------------------------------------------------------------

Syntax
obj.Locate( Str [, Flag ] )
Part

--------------------------------------------------------------------------------
Description
--------------------------------------------------------------------------------

obj A File object returned from a previous call to FUNCky.CreateFile.
Str The string of text to look for.
Flag The case sensitivity to use. Optional. If omitted, TRUE is assumed.


Returns
The file pointer position where the first matching string was found, -1 if an error occurred, -2 if the string was not found.
Description
Locate searches the current file for a specific string of text. The search begins at the current file pointer position and ends when the first occurrence of the string is found, or when the end of file is reached, whichever comes first.
The string to search for is specified via the parameter Str.

The case sensitivity of the search can be specified via the parameter Flag.

When Flag is True, a case sensitive search is performed.

When Flag is False, a non-case sensitive searched is performed.

If Flag is not specified, True is assumed.

If the specified string is found, the file pointer is positioned on the first character in the found string and its offset within the file is returned.

If the specified string is not found, -2 is returned and the file pointer position is unchanged.

If an error occurred while searching for the string, -1 is returned and the file pointer is left in an undetermined position.

If an error occurs, the Error and ErrorMessage properties can be queried for more detailed information.



--------------------------------------------------------------------------------

Tip Use the Skip method to rewind the file pointer to the beginning of the line of text where the string is found so that the whole line of text including the string may be read.
To search for multiple occurrences of text, find the first occurrence, then add the length of the found string to the Offset property to skip over it. Then just repeat the search.


--------------------------------------------------------------------------------


Example

Code: Select all  Expand view

// This example opens a file, searches for the
// word "Gadzooks", and if found, the file
// pointer is rewound to the start of the line
// to read the whole line of text containing the word
Set File = FUNCky.CreateFile()

// Open some text file
If( File.Open("C:\SomeFile.txt", FConst.O_READONLY)) Then

    // Locate the word "Gadzooks" using no case sensitivity
    Offset = File.Locate("Gadzooks", False )

    // Verify found
    If( Offset >= 0) Then

        // Rewind to the beginning of the line
        Offset = File.Skip(0)

        // Read in that line of text
        Str = File.ReadLine()

    End If

    // All done with file
    File.Close()

End If

Mi abuelo decía: Los aviones vuelan porque Dios quiere, y los helicópteros ni Dios sabe porque vuelan.
FWH 16.02, xHarbour 1.2.3, Harbour 3.2.0, WorkShop 4.5, AJ Make 0.30, Borlan BCC 7.00, VisualStudio 2013
User avatar
JmGarcia
 
Posts: 654
Joined: Mon May 29, 2006 3:14 pm
Location: Madrid - ESPAÑA

Re: Buscar texto en un fichero

Postby antolin » Thu Nov 25, 2010 7:53 am

Gracias JmGarcia, es exactamente lo que estaba buscando.

Voy a ver si encutro esas librerías por ahí.
Peaaaaaso de foro...
antolin
 
Posts: 494
Joined: Thu May 10, 2007 8:30 pm
Location: Sevilla

Re: Buscar texto en un fichero

Postby antolin » Thu Nov 25, 2010 9:20 am

Hola JmGarcia

He encontrado la web oficial de FUNCky (muy, muy interesant) y tengo una preguntita tonta, ¿Que librería habría que bajar/comprar, la de CLIPPER o la de XBASE?

Otra cosa ¿Es FREEWARE?

Gracias de antemano
Peaaaaaso de foro...
antolin
 
Posts: 494
Joined: Thu May 10, 2007 8:30 pm
Location: Sevilla

Re: Buscar texto en un fichero

Postby JmGarcia » Thu Nov 25, 2010 9:50 am

antolin wrote:¿Que librería habría que bajar/comprar, la de CLIPPER o la de XBASE?
No hay que linkar nada. Solo instalar los que ellos llaman "REDISTRIBUTABLES" y se te queda instalado en el PC la tecnología COM (Common Object Model).

Un ejemplo de codigo fuente, para la función ChrCount de Funcky, sería algo asi:
Code: Select all  Expand view
/*
obj.ChrCount( Chr, Str )
obj  A FUNCky Object created by a previous call to CreateObject.  
Chr  A string containing the character to search for.  
Str  A string to search.  
Returns The number of times Chr appears within Str. If Chr is not found to be in Str, 0 is returned.
*/

function main()
oFuncky:=CreateObject("FUNCky")
msginfo(oFuncky:ChrCount("t","Esto es un test")) // Visualiza un 3 (el número "t")
msginfo(oFuncky:ChrCount("A", "1234567")) // Visualiza 0 (no hay ninguna "A")
return nil

Otro ejemplo con la función Ping de Funcky:
Code: Select all  Expand view
/*
obj.Ping( Server [, Format ] [, Timeout ] )
obj  A FUNCky Object created by a previous call to CreateObject.  
Server  The name or IP address of the server to ping.  
Format  A format string used to define the output. Optional, the default is "Reply from: xxx.xxx.xxx.xxx RTT: xx TTL: xx.  
Timeout  The number of milliseconds to wait before giving up. Optional. The default is 20 seconds.  
Returns A string containing the ping results or "" if the ping timed out or the server was not found.
*/

msginfo(oFuncky:Ping("www.microsoft.com","",10000)) // Visualiza la IP del sitio.
 


antolin wrote:¿Es FREEWARE?
No, es de pago.
Mi abuelo decía: Los aviones vuelan porque Dios quiere, y los helicópteros ni Dios sabe porque vuelan.
FWH 16.02, xHarbour 1.2.3, Harbour 3.2.0, WorkShop 4.5, AJ Make 0.30, Borlan BCC 7.00, VisualStudio 2013
User avatar
JmGarcia
 
Posts: 654
Joined: Mon May 29, 2006 3:14 pm
Location: Madrid - ESPAÑA

Re: Buscar texto en un fichero

Postby antolin » Thu Nov 25, 2010 10:57 am

Perdona que te de la lata, pero: En la pagina de FUNCKY no hay nada para bajar ni instalar, ¿de donde puedo bajar esa libraría?

Gracias
Peaaaaaso de foro...
antolin
 
Posts: 494
Joined: Thu May 10, 2007 8:30 pm
Location: Sevilla

Re: Buscar texto en un fichero

Postby Willi Quintana » Thu Nov 25, 2010 2:51 pm

Hola sr,,, echale un ojo a este link:
http://www.ousob.com/ng/53guide/ng4bc9b.php
User avatar
Willi Quintana
 
Posts: 1003
Joined: Sun Oct 09, 2005 10:41 pm
Location: Cusco - Perú

Re: Buscar texto en un fichero

Postby Patricio Avalos Aguirre » Thu Nov 25, 2010 2:58 pm

Hola

Al parecer Funky no es para Windows 7

alguien me puede confirmar
Saludos
Patricio

__________________________________________________________________
Version: Harbour 3.2.0dev (r1307082134),Compiler: Borland C++ 5.8.2 (32-bit)
PCode version: 0.3, FWH 13.2
http://www.sialm.cl
User avatar
Patricio Avalos Aguirre
 
Posts: 1059
Joined: Fri Oct 07, 2005 1:56 pm
Location: La Serena, Chile

Re: Buscar texto en un fichero

Postby Ruben Fernandez » Fri Nov 26, 2010 3:18 pm

Antolin: Harbour tiene la libreria hbnf.lib que es la antigua libreria Nanfor.lib

Segun veo tiene buenas posibilidades para lo que necesitas, no se si esta toda convetida en harbour, pero no cuesta nada investigar.

La ng de la libreria, esta aqui junto con la lib para clipper, solo sirve la ng para ver su funcionamiento.
http://www.the-oasis.net/ftpmaster.php3 ... ftplib.htm

Para leer la ng necesitas Expert Guide for Windows (WEG). Probado en Win7.
http://www.davep.org/norton-guides/

Saludos
Gracias y Saludos
Ruben Fernandez - Uruguay
FWH 11.06, Harbour, Borland 5.82
Ruben Fernandez
 
Posts: 366
Joined: Wed Aug 30, 2006 5:25 pm
Location: Uruguay

Re: Buscar texto en un fichero

Postby antolin » Mon Nov 29, 2010 8:09 am

Ok Ruben, muchas gracias.

Lo voy a probar a ver que tal. Porque Funcky 6 tiene buena pinta, pero es muy hermetico y oscuro, he instalado la demo pero no se ni donde estan las librerías, ni si funcionaria, ni nada (tampoco he tenido mucho tiempo).
Peaaaaaso de foro...
antolin
 
Posts: 494
Joined: Thu May 10, 2007 8:30 pm
Location: Sevilla

Re: Buscar texto en un fichero

Postby JmGarcia » Mon Nov 29, 2010 11:13 am

antolin wrote:...he instalado la demo pero no se ni donde estan las librerías...

Como te comente es tecnología COM (Common Object Model). Lo que hace es registrar una DLLs que coloca en el directorio c:\windows\system32 y son: FUNCky16.DLL, FUNCky60.DEP, FUNCky60.DLL y FUNCky60.TLB
Mi abuelo decía: Los aviones vuelan porque Dios quiere, y los helicópteros ni Dios sabe porque vuelan.
FWH 16.02, xHarbour 1.2.3, Harbour 3.2.0, WorkShop 4.5, AJ Make 0.30, Borlan BCC 7.00, VisualStudio 2013
User avatar
JmGarcia
 
Posts: 654
Joined: Mon May 29, 2006 3:14 pm
Location: Madrid - ESPAÑA

Re: Buscar texto en un fichero

Postby antolin » Mon Nov 29, 2010 1:01 pm

Es cierto JmGarcia, aunque no son exactamente los mismos porque es una demo a 90 dias para xbase (lo unico que he encontrado). Lo que me falta ahora son los ficheros de cabecera (.ch), no los encuentro por ningún lado y eso que en e fichero de ayudas esepcifica que .ch hay que utilizar para cada objeto, pero no dice donde están.
Peaaaaaso de foro...
antolin
 
Posts: 494
Joined: Thu May 10, 2007 8:30 pm
Location: Sevilla

Next

Return to FiveWin para Harbour/xHarbour

Who is online

Users browsing this forum: Google [Bot] and 22 guests