Create a function that reads a list correctly

Asked

Viewed 42 times

-2

This function should ask for a name to be used as a search term. If the search movie is in the list, all data from the movie. Otherwise, a message that is not on the list.

This is the function I created to try to resolve the issue but it presents some flaws that I quote below:

def funçao2(n):
    arq = open('ListaFilmes.txt', 'r')
    conteudo = arq.readlines()
    arq.close()

    n = str(input('Digite o nome do filme: '))

    for linha in conteudo:
        linha = linha.split(';')
        for coluna in linha:
            coluna = coluna.split()
            coluna1 = linha[0]
            coluna2 = linha[1]
            coluna3 = linha[2]
            coluna4 = linha[3]
            for elem in coluna:
                if n == elem:
                    print('NOME:',coluna1)
                    print('GÊNERO:',coluna2)
                    print('CLASSIFICAÇÃO:',coluna3)
                    print('ANO DE LANÇAMENTO:',coluna4)
                else:
                    print('O filme não consta na lista')

So that I created, if for example I want to access a film that is in the list, he accesses the movie, but also shows the message 'The movie is not in the list', message this is only to happen if I try to look for a movie that is not in the list, and when I go to look for a movie that is not on the list, this message appears several times.

You can help me to fix the code so that if I search for the film in the list, the program shows only the searched movie, and if I look for a movie that is not in the list, the program shows the message 'The movie is not in the list' only once?

1 answer

2

Since your file seems to be separated by semicolons, I suggest you use the module csv to read it instead of splitting lines manually.

To solve your problem, one of the most elegant ways is to use the else in the for:

import csv

pesquisa = input('Digite o nome do filme: ')

with open('ListaFilmes.txt', newline='') as f:
    cf = csv.DictReader(f, ['nome', 'genero', 'classificacao', 'ano'], delimiter=';')
    for filme in cf:
        if pesquisa in filme['nome']:
            print(filme['nome'], filme['genero'], filme['classificacao'])
            break
    else: # else do for
        print('O filme não consta na lista')

As you can see, the else is aligned with the for, therefore, it will only be executed if the for reach the end.

  • you could put so that I do not need to search the full name? for example I searched 'o' and appear 'the lord of the rings'

  • @Joãovictorrodrigues just look pesquisa in filme['nome']... edited the answer...

Browser other questions tagged

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