How to find a string in a python txt

Asked

Viewed 123 times

0

I wanted that with this code I could go through my txt file and show all the same words (which is autonomy). I don’t know if it’s possible and the only way I can is to make a print(pesquisar_registro(file,word)) and so only shows the first word and shows nothing else.

file = 'aeronaves.txt'
word = input("Autonomia: ").lower()      
def pesquisar_registro( arq, txt ):
    nome = ""
    with open( arq, 'r' ) as a:
        for linha in a:
            linha = linha.strip('\n')
            if nome == "":
                if txt in linha.split():
                    nome = linha
                else:
                    registro = linha.split(',')
                    dic = { "Nome"   : registro[0],  \
                            "Autonomia"        : nome,         \
                            "Capacidade"  : registro[1]}
                    return dic;
    return None;
print (pesquisar_registro( file , word ))

my txt is saved this way:

123
boing747,123
123
boing567,567
345
boing456,567
  • Your code is riddled with errors, already tried to run it to see what happens?

  • I’ve fixed some misspelled indentations but yes it works but not only want the first word equal I wanted all the same words that appear in txt

2 answers

0

You can divide your problem into two parts. The first part would be responsible for loading the contents of the file fully into memory, putting together a list of dictionaries, see only:

def carregar_arquivo(arq):
    ret = []
    dic = {}
    with open( arq, 'r' ) as a:
        for n, linha in enumerate(a):
            linha = linha.strip()
            if n % 2:
                dic['Nome'], dic['Capacidade'] = linha.split(',')
                ret.append(dic)
                dic = {}
            else:
                dic['Autonomia'] = linha
    return ret

Testing:

dados = carregar_arquivo('aeronaves.txt')
print(dados)

Exit:

[
    {'Autonomia': '123', 'Nome': 'boing747', 'Capacidade': '123'},
    {'Autonomia': '123', 'Nome': 'boing567', 'Capacidade': '567'},
    {'Autonomia': '345', 'Nome': 'boing456', 'Capacidade': '567'}
]

Now that you have the contents of your file in memory, searching for an occurrence in this list of dictionaries would be very simple:

def pesquisar( arquivo, txt ):
    ret = []
    dados = carregar_arquivo(arquivo)
    for i in dados:
        if any(txt in v for k, v in i.items()):
            ret.append(i)
    return ret

Testing:

ocorrencias = pesquisar('aeronaves.txt', 'boing747')
print(ocorrencias)

Exit:

[{'Autonomia': '123', 'Nome': 'boing747', 'Capacidade': '123'}]

See working on Repl.it

0


Your code is very broken, you won’t get much with it, I advise you to try to rewrite it, but if you want the result using the same or even see how you could do so that your right code made some modifications, see if it matches.

file = 'diretorio/test.txt'
word = input("Autonomia: ").lower()


def pesquisar_registro(arq, txt):
    with open(arq) as a:
        for linha in a:
            linha = linha.strip('\n')
            if ',' not in linha:
                nome = linha
            elif ',' in linha and (txt in linha or txt in nome):
                registro = linha.split(',')
                dic = {"Nome": registro[0],
                       "Autonomia": nome,
                       "Capacidade": registro[1]}
                yield dic
    return None


for p in pesquisar_registro(file, word):
    print(p)

Browser other questions tagged

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