Help python by taking only the last data from the list

Asked

Viewed 445 times

0

I have a website and I need a name separation system:last name with list, the data is in a txt and I normally import the data is for example: maria:Carla Joao:lima wanted to be able to separate as follows when this print in data it would leave in different lists since the data are each in a line ['maria','Carla'] and ['Joao,'file'], and also separate as follows by variables, name = names[0]when giving a print in name would show ['Joao'] ['maria'],the first part of the code at the time ta so, it is only separating the first name:surname from the list also would 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(":")

1 answer

2


You can create an object with the attributes name and surname

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

after this you will need to work with arrays, the idea is for each row within your foreach 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 within your array nomes

To access the items you can test:

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

You can convert this list to json, for this 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 it is possible to make the conversion to json

import json
jsonstr = json.dumps(para_dict(nomes))
  • Thanks! I was in need

  • I have another question, I am trying to send the data after to my site with import requests, however it is only sending the last name:last name and the first ones give error, will be q the problem is in this list system?

  • actually has to do with the serialization of the object, basically you need to change the serialization of the object, the best way to send to another system through requests is envialos as json, I will edit the answer

  • Edited answer, you will need to change the way to build your object, create the method that transforms the object to Dict and then yes can get the json, json vc can send via request

Browser other questions tagged

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