How to find a certain value in a line that contains a keyword - python

Asked

Viewed 37 times

-1

How could I find a value on a given line that contains a keyword

Example (This is the Mirror file)

 COTIA CENTRO

EXTRACT 05978754

ITEM 1 ITEM 2 ITEM 3

MRO: 082545444

I would like to know how to find this value of what is in front of the extract , Example

If the number such is in the same row as the Extract it returns true , if it is not false returns

This is my code

import re
import json
import os
import os.path
from time import sleep

with open('P:/portal/cupons/API/valores_api.json', 'r') as jsonFileLeitura:
    dadosJson = json.load(jsonFileLeitura)
    valor = dadosJson['valor']


def procura_cupom():
    txt = open("P:/portal/cupons/Arquivos_Espelho/arqEspelho.txt", "r").read()

    # usando finditer ele retorna a posição da palavra

    # Localiza o inicio do cupom
    x = re.finditer(r".*COTIA CENTRO", txt)
    # Localiza o fim do cupom
    z = re.finditer(r"OPR.*", txt)

    espelhos = list(zip(x, z))

    # Testando o valor específico para cada espelho
    for espelho in espelhos:

        txt_espelho = txt[espelho[0].span()[0]: espelho[1].span()[1] + 1]

        if "{}".format(valor) in txt_espelho:
            if os.path.isfile("P:/portal/cupons/Arquivos_Espelho/espelhado.txt"):
                open("P:/portal/cupons/Arquivos_Espelho/espelhado.txt", 'w').close()
            sleep(1)
            # Escreve o Cupom caso encontrado, em um novo arquivo de texto
            open("P:/portal/cupons/Arquivos_Espelho/espelhado.txt", "w+").write(txt_espelho)

        else:
            pass


if True:
    procura_cupom()

Thank you!

1 answer

0

If the file has only the line in this format: "EXTRACT 05978754"

Just read the file line by line:

import re

for linha in open("P:/portal/cupons/Arquivos_Espelho/arqEspelho.txt", "r").readLines():
    if "EXTRATO" in linha.split():
       if re.match(r'^([\s\d]+)$', linha):
          return True
   

Browser other questions tagged

You are not signed in. Login or sign up in order to post.