how to correctly pass the txt file data to a python list?

Asked

Viewed 88 times

0

I am creating a simple program that reads data from a file .txt, passing them to a list. Then the program asks for a keyword to check if it exists in the list and show which position it is in.

A priori is giving to take the data from the file and pass to the list, but when it runs the code to search the keyword the code only works right when the keyword is at position 0 of the list. When it is in position 1 up, it no longer runs right, not finding the keyword even typing straight.

I made another file .py with the same code, but with the list created in the code itself - without taking the data from the text file - and the program worked correctly, finding the position of any element that had in the list.

So I think the error is in the code that gets the file data .txt and creates the list. But I have no idea what’s wrong, because I have already redone and tested this code several times and did not find the error.

Here’s the problematic code:

Lista = []

with open(Arquivo, 'r', encoding='UTF-8') as f:
    Dados = f.readlines()

for linha in Dados:
    for i in linha.split(','):
        Lista.append(i)
        print(Lista)

From what I see, the list creation is apparently normal, but the code that searches the keyword is not able to iterate across the list.

This is the code that searches for the keyword in the list:

for item in Lista:
    print(item, Lista.index(item))

    if item == Keyword:
       print("Foi encontrada a palavra-chave na lista, na posição: ", Lista.index(Keyword))

Updating

I changed the search code to this one:

for item in Lista:
print(item, Lista.index(item))
if item != Keyword:
    print('A palavra-chave não está na lista')
else:
    print("Foi encontrada a palavra-chave na lista, na posição: ", Lista.index(Keyword))

Now I got the following answer:

Enter a list in format . txt: C: Users Suu Documents List of games.txt

['to']

['a', ' b']

['a', ' b', ' c']

['a', b', c', d']

Give a keyword: b

to 0

The keyword is not on the list

b 1

The keyword is not on the list

c 2

The keyword is not on the list

d 3

The keyword is not on the list

Process finished with Exit code 0

I don’t know what else to do, honestly... I think I’m really gonna give up. ='(

Updating

Anyone who wants to see the full code can access this link from my github: https://github.com/Suu021/Python-Projects-beginner/blob/Suu021-patch-1/Busca%20per%20Brute%20Force.py

  • And what is the content of the txt file?

  • Anyway, it can be simpler: https://repl.it/@hkotsubo/Ripecoolproject#main.py

2 answers

1

The following code is working:

lista1 = [1,2,2,3,4,5,6,6,6,6,7,8,9,10]

keyword = 2

for index in range(0,len(lista1)):
    # print(index)
    
    if lista1[index] == keyword:
        print(f'Foi encontrada a palavra-chave na lista na posição {index}')

outworking:

Foi encontrada a palavra-chave na lista na posição 1
Foi encontrada a palavra-chave na lista na posição 2

Replicating your code, what I imagine happens is that the method Lista.index(Keyword) returns only the same value because: 1) Keyword is constant (I imagine) and 2) this method returns only the first comparison it gives True (I don’t know if that’s right)

  • "1) Keyword is constant (I imagine)" Keyword is a variable, the user chooses a keyword. "2) this method returns only the first comparison that gives True (I don’t know if that’s right)" Yes, is to return the first comparison that gives True. The problem is that when the list is created from the data attachment of a txt file, when the code starts iterating through the list, it is iterating only the first element at position 0. It is not comparing with the rest of the elements within the list...

0

Today I managed to make my code run the way I wanted, I would like to expose my solution to help someone who has a similar problem:

with open(Arquivo, 'r', encoding='UTF-8') as f:
dados = f.readlines()
for linha in dados:
    for i in linha.split(', '):
        lista.append(i)

The problem was exactly on line 4 of this piece of code, which before was for i in linha.split(','):, that way when giving the split the words went to the list with a space between them so that the informed Keyword did not match those words from the list.

Ex: keyword = 'b', lista = ['a', ' b', ' c', ' d'].

The way it is now for i in linha.split(', '): the list gets: lista = ['a', 'b', 'c', 'd'], without spaces between words.

Browser other questions tagged

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