Help python getting only the last data from the list

0

I have a website and need a name separation system: surname with list, the data stays in a txt and I normally import the data stand for example: maria: carla joao: lima I wanted to be able to separate as follows when giving this print in data he would leave it in different lists since the data are each in a line ['maria', 'carla'] and ['joao,' lima '], and also separate it from the following the first part of the code at the moment ta so, it is only separating the name of the code and the name of the code. first name: surname of list would also like to solve this:

    arquivo=raw_input("Digite o nome do arquivo para separar: ")
    ler=open(arquivo)
    with ler as f:
     for line in f:
       nome, sobrenome = line.split(":")
    
asked by anonymous 28.04.2017 / 04:39

1 answer

2

You can create an object with the attributes first and last name

class Objeto(object):
    def __init__(self):
        self.nome = ''
        self.sobrenome = ''

After this you will need to work with arrays, the idea is for each line inside your forEach to mount a new object with the filled attributes and add them to this array, with some changes your code would look like this:

arquivo=raw_input("Digite o nome do arquivo para separar: ")
    ler=open(arquivo)
    nomes = []
    with ler as f:
        for line in f:
            obj = Objeto()
            obj.nome, obj.sobrenome = line.split(":")
            nomes.append(obj)

Now you have all the names inside your array nomes

To access the item you can test:

for item in nomes:
    print('nome: ' + item.nome + ' , Sobrenome: ' + item.sobrenome)

You can convert this list to json , so you will need to create the following method (Object for dict):

def para_dict(obj):
    if hasattr(obj, '__dict__'):
        obj = obj.__dict__
    if isinstance(obj, dict):
        return { k:para_dict(v) for k,v in obj.items() }
    elif isinstance(obj, list) or isinstance(obj, tuple):
        return [para_dict(e) for e in obj]
    else:
        return obj

Now you can convert to json

import json
jsonstr = json.dumps(para_dict(nomes))
    
28.04.2017 / 05:34