Remove characters from python lists

Asked

Viewed 80 times

-1

Hello I have a code that le two files one txt and a XML and then checks a string inside a list

THE XML:

<nfeProc xmlns="http://www.portalfiscal.inf.br/nfe" versao="4.00">
<NFe xmlns="http://www.portalfiscal.inf.br/nfe">
<infNFe Id="NFe35200861974911000104550010000742491174625832" versao="4.00">
<ide>
...
</ide>
<emit>
...
</emit>
<dest>
...
</dest>
<det nItem="1">
<prod>
<cProd>20517-0</cProd>
<cEAN>7897748715180</cEAN>
<xProd>SAFEBLOCK FUSE BLOQUEADOR AUTOMOTIVO (COM FUSIVEL DE EMERGENCIA / SIRENE OPCIONAL)</xProd>
<NCM>85123000</NCM>
<CEST>0110000</CEST>
<CFOP>5401</CFOP>
<uCom>PC</uCom>
<qCom>20.0000</qCom>
</prod>

THE TXT:

0|7897748715180|||||20

My code:

def tratar_linha(linha):
    dados = linha.strip('\n').split('|||||')
    if len(dados) > 0:
        return dados
    return None
lista = []
#função do EAN
#------------------------------------------------------------------------------------------
def search (lista, valor):
    return [(lista.index(x), x.index(valor)) for x in lista if valor in x]
#função do EAN
#------------------------------------------------------------------------------------------
#text = input("Coloque o diretorio do fisico: ").strip('"')
with open(r"C:\Users\Expedição\Downloads\74249.txt","r", encoding="utf8") as arquivo:
    for linha in arquivo:
        dado = tratar_linha(linha)
        if dado is not None:
            lista.append(dado)
#localiza arquivo,lista todos os itens
#------------------------------------------------------------------------------------------
#XML = input("Coloque o diretorio do XML: ").strip('"')
tree = ET.parse(r"C:\Users\Expedição\Downloads\74249.xml")
root = tree.getroot()
    Contagem = 1
    ns = {'nfe': 'http://www.portalfiscal.inf.br/nfe'}
    for det in root.findall('.//nfe:det', ns):
        nItem = det.attrib['nItem']
        quantidade = det.find('.//nfe:qCom', ns).text.strip('000').strip('.')
        EAN = det.find('.//nfe:cEAN', ns).text
        if EAN is not None:
            FEAN =  "0|" + EAN
    #importa XML, obtem os campos EAN,quatidade    
    #------------------------------------------------------------------------------------------
            if search(lista, FEAN):
                print(f"{Contagem} - EAN encontrado: {EAN}")
                lista.remove(FEAN)
            else:
                print(f"{Contagem} - EAN INVALIDO: {EAN}")

I tried to use the lista.remove(FEAN) but this giving this mistake and I do not know how to fix.

File "c:/Users/Expedição/Videos/python/Consulta.py", line 49, in <module>
    lista.remove(FEAN)
ValueError: list.remove(x): x not in list

1 answer

0


Just check your list:

lista = []
with open(r"texto.txt", "r", encoding="utf8") as arquivo:
    for linha in arquivo:
        dado = tratar_linha(linha)
        if dado is not None:
            lista.append(dado)

print('lista=', lista)

Upshot:

lista= [['0|7897748715180', '20']]

That is, the list has an element, which is another list (and this contains 2 elements: the string '0|7897748715180' and the string '20'). This is because split returns a list, which you entered in lista. And she only has two elements because you did the split for '|||||' (I mean, he used '|||||' - a sequence of 5 characters | - as the separator).


Anyway, if you want to search for the code that is in txt, put it directly in the list. Do the split for | and only include non-empty elements :

def tratar_linha(linha):
    dados = linha.strip('\n').split('|')
    if len(dados) > 0:
        return dados
    return None

lista = []
with open(r"texto.txt", "r", encoding="utf8") as arquivo:
    for linha in arquivo:
        dado = tratar_linha(linha)
        if dado is not None:
            lista.extend([x for x in dado if x]) # exclui as strings vazias

So the list will have the '0', '7897748715180' and '20' as separate elements.


Or take only the second field of the line, which seems to be what you want:

def tratar_linha(linha):
    dados = linha.strip('\n').split('|')
    if len(dados) >= 2:
        return dados[1] # retorna o segundo campo (7897748715180)
    return None

lista = []
with open(r"texto.txt", "r", encoding="utf8") as arquivo:
    for linha in arquivo:
        dado = tratar_linha(linha)
        if dado is not None:
            lista.append(dado) # insere o campo (7897748715180)

So I just return a field (the 7897748715180).


Having the list only with the information that interests me, the search becomes easy, not needing to concatenate the zero in front and not using an extra function with index or any of that:

for det in root.findall('.//nfe:det', ns):
    nItem = det.attrib['nItem']
    quantidade = det.find('.//nfe:qCom', ns).text.strip('000').strip('.')
    EAN = det.find('.//nfe:cEAN', ns).text
    if EAN is not None:
        if EAN in lista: # se está na lista
            print(f"{Contagem} - EAN encontrado: {EAN}")
            lista.remove(EAN)
        else:
            print(f"{Contagem} - EAN INVALIDO: {EAN}")

See that to check if an item is in the list, just use the operator in.

  • your proposal is well valid but in my case in particular I need the lista have the int tbm (20)

Browser other questions tagged

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