Go through Array and remove words - Python

Asked

Viewed 187 times

0

I created a list using a text file and I need to remove all words that are less than 3 characters and more than 8.

I’m having doubts about how to go through the list and create another list without the words that don’t meet the established criteria

This is what I’ve done so far:

 `if __name__ == '__main__':

    with open('senhas.txt') as senha:                                           # ABRE O ARQUVO DE TEXTO COM AS PALAVRAS
        words = []                                                      # CRIA UMA NOVA LISTA PARA ARMAZENAR AS PALAVRAS
        for n in senha:                                # ESTRUTURA DE REPETIÇÃO PARA ADICIONAR AS PALAVRAS NA LISTA NOVA
            words.append(n.strip())                                                        # RETIRA OS ESPAÇOS EM BRANCO





','.join(words)  # SEPARA AS PALAVRAS EM APENAS UMA LINHA.

for i in range(len(words)):
    words[i] = words[i].lower()  # CONVERTE AS PALAVRAS EM MÍNUSCULO'

and the words with the file are here: https://pastebin.com/FY3UxZtK

2 answers

1


Hello,

Instead of removing the elements according to the established rules, you may not even add them, so do so:

for n in senha:
    password = n.strip().lower()
    length = len(password)

    if (length >= 3 and length <= 8):
        words.append(password)

The above code only adds words with size >= 3 and <= 8, and also leaves the word with lowercase letters with the . Power(), all at once!

1

To read each line of a file (word) and add only lines that have sizes between 3 and 8 on a list:

with open('senhas.txt') as f:
    words = []
    for ln in f:
        ln = ln.strip()
        if 3 <= len(ln) <= 8:
            words.append(ln)

Or even:

with open('senhas.txt') as f:
    words = [ln.strip() for ln in f if 3 <= len(ln.strip()) <= 8]

To convert the case of all words contained in the list to lower case:

words = list(map(str.lower, words))

All together in one line:

with open('senhas.txt') as f:
    words = [ln.strip().lower() for ln in f if 3 <= len(ln.strip()) <= 8]

See working on Repl.it

Browser other questions tagged

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