How to open a txt file and use it to print what I want

0

I made the following code:

def caixaAlta(texto):
    return texto.upper()

def ultimosNomes(nomeInteiro):
    lista = nomeInteiro.split(' ')
    if lista[-1].lower() == 'junior' or lista[-1].lower()=='sobrinho' \
       or lista[-1].lower()=='neto' or lista[-1].lower()=='filho':
        return caixaAlta(lista[-2])+" "+caixaAlta(lista[-1])
    else:
        return caixaAlta(lista[-1])

def primeirosNomes(nomeInteiro):
    lista = nomeInteiro.split(' ')
    nome=''
    if lista[-1].lower() == 'junior' or lista[-1].lower()=='sobrinho' \
     or lista[-1].lower()=='neto' or lista[-1].lower()=='filho':
        for i in range(len(lista)-2):
            nome = nome + inicial(lista[i])
    else:
        for i in range(len(lista)-1):
            nome = nome + inicial(lista[i])
    return nome

def inicial(nome):
    for i in nome:
        if nome=='da' or nome=='do' or nome=='de' \
           or nome=='das' or nome=='dos' or nome=='e':
            nome=nome.replace(i,".d")
            return nome.lower()+' '

        else:
            return nome[0].upper()

def referencia(nomeInteiro):
    return ultimosNomes(nomeInteiro)+','+primeirosNomes(nomeInteiro)


print(referencia(input('Digite nome do autor: ')))

Your output will be as follows:

> Digite nome do autor: Joao Joca da Silva  <- o nome eu digito
> SILVA,JJ.da <- isso que imprime

This way I did I create names and it prints the way I want, but how do I just use names from a txt file and print it in the same way?

    
asked by anonymous 16.10.2018 / 15:34

1 answer

2

Try This:

Create a file named .txt file with the names you want, then do:

import  codecs
wordList = codecs.open('Arquivo.txt' , 'r').readlines()
for w in wordlist:
    print(referencia(w[:-1]))
  

Pythonism:

Nearly all languages have conventions and python is no different, it would be interesting if you read the guide of coding style python , to cite an example, instead of using camelcase ( minhaVariavel ), use snakecase ( minha_variavel )

In python you do not need that lot of ifs to see if something is in a list, in the first sequence of ifs of your code, instead of doing:

if lista[-1].lower() == 'junior' or lista[-1].lower()=='sobrinho' \
   or lista[-1].lower()=='neto' or lista[-1].lower()=='filho':
    return caixaAlta(lista[-2])+" "+caixaAlta(lista[-1])
else:
    return caixaAlta(lista[-1])

You can do

if lista[-1].lower() in ['junior', 'sobrinho', 'neto', 'filho']

See that you can also read this list from a text file, just as you did to read the input file of the names.

Note.
This is just a way to read a txt file in python, I chose randomly (because I already answered something with codecs) but there are other ways to do that.

To complement, see tb this answer , here in STOpt.

    
16.10.2018 / 16:07