0

quiero consultar, ¿cómo puedo hacer para poder omitir todo el contenido que se obtiene luego de un string indicado?

En este caso necesitaría omitir todo el contenido posterior al siguiente string: '----- Original message -----'

Éste código que añado abajo representa a un analizador de múltiples archivos, el descarte de contenido serviría para que el archivo generado o de salida no fuera tan pesado.

import os
import glob
import re

path = 'D:/Python/detectar_coincidencias/1/procesar1'
extension = '*.txt'

def comparar_linea(file1, file2):
    data1 = [line.strip() for line in file1.readlines()]
    data2 = [line.strip() for line in file2.readlines()]
    same = set(data1).intersection(data2)
    omitir = '----- Original message -----'
    s = re.match(r'^----- Original message -----*',omitir).group(0)
    print(s)
    same.discard(s)
    same.discard('\n')
    same.discard('MIME-Version: 1.0')
    same.discard('Return-Path: <>')
    same.discard('DKIM-Signature: v=1; a=rsa-sha1; c=relaxed/relaxed;')
    same.discard('Precedence: bulk')
    same.discard('Content-Type: multipart/alternative;')
    same.discard('Content-Transfer-Encoding: quoted-printable')
    same.discard('Content-Type: text/html;')
    same.discard('Content-Transfer-Encoding: base64')
    same.discard('Content-Type: text/plain; charset=UTF-8')
    same.discard('padding-top:0px; font-family: Arial, Helvetica, sans-serif; color: =')

    return same

def buscarCoincidencias(path, extension):
    with open('coincidencias.txt', 'w') as file_out:
        os.chdir(path)
        files = glob.glob(extension)
        for i in range(len(files)):
            for j in range(i+1, len(files)):
                with open(files[i]) as file1:
                    with open(files[j], 'r') as file2:
                        same = comparar_linea(file1, file2)
                        for contain in same:
                            if not contain:
                                #print (contain)
                                pass
                            else:
                                file_out.write(files[i] + "-"+ files[j] + ": "+str(same)+"\n")


buscarCoincidencias(path, extension)

EDIT: Dejo dos ficheros de referencia como muestra:

Archivo: 3613718093.txt

Received: from mail-io0-f194.google.com ([209.85.223.194]) by gestorb.com with MailEnable ESMTP; Sun, 1 Jan 2017 22:50:48 +0000
Received: by mail-io0-f194.google.com with SMTP id m204so20550870ioe.3
        for <[email protected]>; Sun, 01 Jan 2017 14:50:40 -0800 (PST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=googlemail.com; s=20161025;
        h=mime-version:from:to:auto-submitted:subject:references:in-reply-to
         :message-id:date:content-transfer-encoding;
        bh=W+qH36Fk2yyk5wRiHgSgrgLvrrwN4RqCPi7/UQLBq6o=;
        b=MXKVWBcGzHeM42yZUNaq8gkJ0LeqED/sW5NJVTuoziEnu8cyYJRh22qVXCn15kA2CM
         IVVaSmC6kUtWMeeRyoVztIoiL6FmS8an5u0EIx+4CAJczvhkbapaKwfxhOPDq/DKvQMj
         LsryeNHOnEfJtP+X4mjKej/nKiVuuOrFCXaLXaTV0rbS1NtFUayaKPl4FrKG7pnUMNm5
         cUwzsM58//jB6EeqSLahEXTvvi7NcJ4OJE6K6kXmId+0CB77HangCut7al6Zzq6LRG5+
         oYpRE3k3RS/blysbF0ke6MpXeoWqitJnlDM6SSthMJP3pdenshdmJmNLK9CQhBi/ohuk
         6daw==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=1e100.net; s=20161025;
        h=x-gm-message-state:mime-version:from:to:auto-submitted:subject
         :references:in-reply-to:message-id:date:content-transfer-encoding;
        bh=W+qH36Fk2yyk5wRiHgSgrgLvrrwN4RqCPi7/UQLBq6o=;
        b=Se1QyMN9s8XaMvvwqTKUmMj+VkKLwmVekaCCyeFLH1yU5hx8TVokDCm77B3sK7W0M9
         /1pTbTZ+ifo/+0x6jUQnYwylXLrDbqwcFiVAO4EmzvsSfPDY+3mF8SBch+aybmhZP4iK
         REMv1ng+5K4sfTd52ptHV1rSPCBGXz9nsxBtG1o6PMshWYLqbB7EcPoSNUZ36wjf8Y+/
         N3bm8glKOUPy1ZxxpnCDd9rhfZWQKrJrIamaDCjOQ/ZFpsyGqTr6iwQ8N9ZzmcJEheGD
         TGJ69wZaT+db0+ORj9dNe+dIeP84nt9UXMcWQ5Ml1/0xDTmeNrrMJaYzkPS8+k3ir229
         uEUg==
X-Gm-Message-State: AIkVDXKRepNHZHttT4XYn6w0nd2bPa6La1QCkNWrYJnpRnxANQL2qaJFQSU/XyymG5RPDo1sbd60Ogh8fQYcKZDej9XBlreGAg==
X-Received: by 10.107.53.36 with SMTP id c36mr42994374ioa.55.1483311040137;
        Sun, 01 Jan 2017 14:50:40 -0800 (PST)
MIME-Version: 1.0
Return-Path: <>
Received: by 10.107.53.36 with SMTP id c36mr45618587ioa.55; Sun, 01 Jan 2017
 14:50:40 -0800 (PST)
From: Mail Delivery Subsystem <[email protected]>
To: [email protected]
Auto-Submitted: auto-replied
Subject: Delivery Status Notification (Failure)
References: <[email protected]>
In-Reply-To: <[email protected]>
X-Failed-Recipients: [email protected]
Message-ID: <[email protected]>
Date: Sun, 01 Jan 2017 22:50:40 +0000
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
Precedence: bulk

Delivery to the following recipient failed permanently:

     [email protected]

Technical details of permanent failure:=20
The recipient server did not accept our requests to connect. Learn more at =
https://support.google.com/mail/answer/7720=20
[mail.schwager.cl 74.125.202.121: timed out]
[mail.schwager.cl 2607:f8b0:4001:c0d::79: timed out]

----- Original message -----

Archivo: 3613718356.txt

Received: from mail-io0-f196.google.com ([209.85.223.196]) by gestorb.com with MailEnable ESMTP; Sun, 1 Jan 2017 23:09:48 +0000
Received: by mail-io0-f196.google.com with SMTP id n85so26633689ioi.1
        for <[email protected]>; Sun, 01 Jan 2017 15:09:39 -0800 (PST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=googlemail.com; s=20161025;
        h=mime-version:from:to:auto-submitted:subject:references:in-reply-to
         :message-id:date:content-transfer-encoding;
        bh=HIQgX1RTj/TKByyKminDKBy5T8PVUHm1sP1RQbHdaC0=;
        b=UHLDWXSBFc2dQudp5qWO8bDeCAQ1OkMtUMySIVbwLJm/kq2eH5EjcV1uzgyv++iGHf
         HDT858xfTi1WpwgRe8BrYBzH1ZKER8hs3W6UNa0EiovU5KKzC+0mCobsM4u02RAIBvS7
         M6zCEuFwOx4Qo1q1BLvWjivPlB/uU0DXaw/GZXyM66JFtvNdNJ8Ar0wyoREQ7e3WqOBk
         OhH+Vo1jrYUJZqNuIia9M75i6wkjBRj7o657BrSwkVxWnWHFEsYKuYQWCXXYHY9XSSJy
         hc42P5tAet4YcbDraLmzkk6AgbIXIKpd2oBRoUgDCOrEIYB7NozH410CitiFFcExKW9G
         HdZw==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=1e100.net; s=20161025;
        h=x-gm-message-state:mime-version:from:to:auto-submitted:subject
         :references:in-reply-to:message-id:date:content-transfer-encoding;
        bh=HIQgX1RTj/TKByyKminDKBy5T8PVUHm1sP1RQbHdaC0=;
        b=dMibRtSd9I9qRDPcIq1zTgv8K+1Cp1Npesv3YR/+YqK0RNLQOm7ROCFC9oB1EUDAkq
         OpFmVGTeStSRC1m+TipP+dR+lJm5+L/STYyNh3hw/hQ5lHXETath3NWY30i1RadmVl2r
         knj/tsSNYeNxfUmudYgXvuxmYOAjiA24UABt8ohnApS5Nf66vZA1TIpLuWt0dTlF9WN+
         NansvcO6vtU3qMwEel/p9OVigRqzBPwe2CmN/GBtCRJ4YSa3nfZbodS09iVfunzXazNg
         lDDHH3+q/vS0W88WnIeR2OJpenletkXfd8AoEg59kZVLkRrrwi49g91BK+7GSpVzKfV7
         np1A==
X-Gm-Message-State: AIkVDXKZvekT/SagP6cwcQuFkjAtpnDw0uzZJdmQbOK/cfkJgwOqNk/asra7heGj5ede0UyWcva0/wSEbWloyMVJn7DKD9qWpw==
X-Received: by 10.107.57.193 with SMTP id g184mr51612121ioa.183.1483312179523;
        Sun, 01 Jan 2017 15:09:39 -0800 (PST)
MIME-Version: 1.0
Return-Path: <>
Received: by 10.107.57.193 with SMTP id g184mr54071174ioa.183; Sun, 01 Jan
 2017 15:09:39 -0800 (PST)
From: Mail Delivery Subsystem <[email protected]>
To: [email protected]
Auto-Submitted: auto-replied
Subject: Delivery Status Notification (Failure)
References: <[email protected]>
In-Reply-To: <[email protected]>
X-Failed-Recipients: [email protected]
Message-ID: <[email protected]>
Date: Sun, 01 Jan 2017 23:09:39 +0000
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
Precedence: bulk

Delivery to the following recipient failed permanently:

     [email protected]

Technical details of permanent failure:=20
The recipient server did not accept our requests to connect. Learn more at =
https://support.google.com/mail/answer/7720=20
[smtp.lanacion.cl 200.27.65.6: timed out]

----- Original message -----

X-Gm-Message-State: AIkVDXIWpDz3I8KoBelaNKLZTexiQqF3910SShrIa8Gb1atFpYqhdpB=
e1dd/tl3ZCs2sVFLzxmnWT8aTfX8xbB+DcHiUEcUigfgcrGMV2osds13d1s8YymPezhk5BSOPHN=
BsQsTUREVPDL20okyCJJn7YZnYHkx9Odc=3D
X-Received: by 10.107.57.193 with SMTP id g184mr23890718ioa.183.14827031096=
64;

Me gustaría que todo lo escrito después de ----- Original message ----- no lo tenga en cuenta.

Saludos!

2 respuestas 2

2

Parece que hay varios problemas.

  • Usar solo la información antes del patrón.
  • Guardar solo la información relevante.

Para el primer problema he creado la función corta que solo usa la información del fichero hasta que encuentra el patrón.

En la segunda parte, creo que tu problema es que estás repitiendo información en el fichero de salida de forma innecesaria. Si lo que quieres obtener en el fichero de salida solo son las coincidencias de líneas entre dos ficheros para la información que se encuentra delante del patrón en cada uno de los ficheros deberías modificar la línea:

file_out.write(files[i] + "-"+ files[j] + ": "+str(same)+"\n")

[última línea de la función buscarCoincidencias]

En lugar de copiar el contenido de contain estás copiando todo el set same provocando que en cada iteración tengas la misma información repetida.

He modificado un poco la función buscarCoincidencias para que haga lo que creo que necesitas.

El código final sería así:

import os
import glob
import re

path = 'D:/Python/detectar_coincidencias/1/procesar1'
extension = '*.txt'

def corta(fileobj):
    data = []
    for line in fileobj.readlines():
        if '----- Original message -----' in line:
            break
        else:
            data.append(line.strip())
    return data

def comparar_linea(file1, file2):
    data1 = corta(file1)
    data2 = corta(file2)
    same = set(data1).intersection(data2)
    same.discard('\n')
    same.discard('MIME-Version: 1.0')
    same.discard('Return-Path: <>')
    same.discard('DKIM-Signature: v=1; a=rsa-sha1; c=relaxed/relaxed;')
    same.discard('Precedence: bulk')
    same.discard('Content-Type: multipart/alternative;')
    same.discard('Content-Transfer-Encoding: quoted-printable')
    same.discard('Content-Type: text/html;')
    same.discard('Content-Transfer-Encoding: base64')
    same.discard('Content-Type: text/plain; charset=UTF-8')
    same.discard('padding-top:0px; font-family: Arial, Helvetica, sans-serif; color: =')
    return same

def buscarCoincidencias(path, extension):
    with open('coincidencias.txt', 'w') as file_out:
        os.chdir(path)
        files = glob.glob(extension)
        for i in range(len(files)):
            for j in range(i+1, len(files)):
                with open(files[i]) as file1:
                    with open(files[j], 'r') as file2:
                        same = comparar_linea(file1, file2)
                        inicio = False
                        for contain in same:
                            if contain:
                                if not inicio:
                                    file_out.write(files[i] + "-"+ files[j] + ": ")
                                    inicio = True
                                file_out.write(contain + ',,,')
                        file_out.write('\n') 

buscarCoincidencias(path, extension)

Como separador de las líneas coincidentes entre dos ficheros he usado ,,,. Modifícalo como consideres.

6
  • muchas gracias por tu respuesta, como podría implementarlo con mi código porque el interprete me brinda un error al querer implementarlo AttributeError: 'set' object has no attribute 'find'
    – Hugo
    Commented el 3 ene. 2017 a las 15:30
  • Si pones un ejemplo de los ficheros que quieres comparar y qué es lo que realmente quieres obtener como resultado final será más fácil darte una respuesta más concreta. Commented el 3 ene. 2017 a las 21:11
  • Gracias por responder y ayudarme, he editado mi consulta añadiendo dos archivos de referencia, lo ideal es que todo lo que esté después de "----- Original message -----" no lo tenga en cuenta
    – Hugo
    Commented el 4 ene. 2017 a las 12:19
  • He actualizado la respuesta. Por favor, si sigue sin ser lo que buscas coméntalo a ver si llegamos a la solución final. Commented el 4 ene. 2017 a las 14:09
  • @kijocorreoso muchas gracias por la ayuda, realmente esta fue una solución para mi, el archivo disminuyo de 40 MB a 91 Kb ;) Muchas gracias!!
    – Hugo
    Commented el 4 ene. 2017 a las 16:12
0

He mejorado la sección de comparar_linea() para que haga el descarte haciendo un bucle for:

import os
import glob
import re

path = 'D:/Python/detectar_coincidencias/1'
extension = '*.txt'

def corta(fileobj):
    data = []
    for line in fileobj.readlines():
        if '----- Original message -----' in line:
            break
        elif '------ This is a copy of the message, including all the headers. ------' in line:
            break
        elif 'This is a MIME-encapsulated message.' in line:
            break
        elif 'This is a multi-part message in MIME format.' in line:
            break
        elif '<html>' in line:
            break
        else:
            data.append(line.strip())
    return data

def comparar_linea(file1, file2):
    data1 = corta(file1)
    data2 = corta(file2)
    same = set(data1).intersection(data2)
    discard = ['\n','MIME-Version: 1.0','Return-Path: <>','DKIM-Signature: v=1; a=rsa-sha1; c=relaxed/relaxed;','Precedence: bulk','Content-Type: multipart/alternative;','Content-Transfer-Encoding: quoted-printable','Content-Type: text/html;','Content-Transfer-Encoding: base64','Content-Type: text/plain; charset=UTF-8','padding-top:0px; font-family: Arial, Helvetica, sans-serif; color: =','Auto-Submitted: auto-replied','message-id:date:content-transfer-encoding;','X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;','DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;','Subject: Delivery Status Notification (Failure)','d=1e100.net; s=20161025;','From: Mail Delivery Subsystem <[email protected]>','h=x-gm-message-state:mime-version:from:to:auto-submitted:subject','h=mime-version:from:to:auto-submitted:subject:references:in-reply-to','Subject: Mail delivery failed: returning message to sender','This message was created automatically by mail delivery software.','recipients. This is a permanent error. The following address(es) failed:','A message that you sent could not be delivered to one or more of its']
    for descartar in discard:
        same.discard(descartar)
    return same

def buscarCoincidencias(path, extension):
    with open('coincidencias.txt', 'w') as file_out:
        os.chdir(path)
        files = glob.glob(extension)
        for i in range(len(files)):
            for j in range(i+1, len(files)):
                with open(files[i]) as file1:
                    with open(files[j], 'r') as file2:
                        same = comparar_linea(file1, file2)
                        inicio = False
                        for contain in same:
                            if contain:
                                if not inicio:
                                    file_out.write(files[i] + "-"+ files[j] + ": ")
                                    inicio = True
                                file_out.write(contain + '[|||]')
                        file_out.write('\n')
                        file_out.write('\n') 

buscarCoincidencias(path, extension)

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.