maggior parte delle soluzioni qui sono solo riformattare i dati nel file che si sta leggendo. Forse è tutto ciò che vuoi.
Se si desidera effettivamente analizzare i dati, inserirli in una struttura dati.
Questo esempio in Python:
data="""\
Name: John Doe2
address : 123 Main St, Los Angeles, CA 95002
phone: 213-123-1234
Name: John Doe1
address : 145 Pearl St, La Jolla, CA 92013
phone: 858-123-1233
Name: Billy Bob Doe3
address : 454 Heartland St, Mobile, AL 00103
phone: 205-123-1232""".split('\n\n') # just a fill-in for your file
# you would use `with open(file) as data:`
addr={}
w0,w1,w2=0,0,0 # these keep track of the max width of the field
for line in data:
fields=[e.split(':')[1].strip() for e in [f for f in line.split('\n')]]
nam=fields[0].split()
name=nam[-1]+', '+' '.join(nam[0:-1])
addr[(name,fields[2])]=fields
w0,w1,w2=[max(t) for t in zip(map(len,fields),(w0,w1,w2))]
Ora si ha la libertà di ordinare, modificare il formato, messo in banca dati, ecc
Questo stampa il formato con cui i dati, in ordine:
for add in sorted(addr.keys()):
print 'Name: {0:{w0}} Address: {1:{w1}} phone: {2:{w2}}'.format(*addr[add],w0=w0,w1=w1,w2=w2)
Stampe:
Name: John Doe1 Address: 145 Pearl St, La Jolla, CA 92013 phone: 858-123-1233
Name: John Doe2 Address: 123 Main St, Los Angeles, CA 95002 phone: 213-123-1234
Name: Billy Bob Doe3 Address: 454 Heartland St, Mobile, AL 00103 phone: 205-123-1232
Questo è ordinato in base al cognome, nome utilizzato nella chiave dict.
Ora Stampa esso allineati secondo prefisso:
for add in sorted(addr.keys(),key=lambda x: addr[x][2]):
print 'Name: {0:{w0}} Address: {1:{w1}} phone: {2:{w2}}'.format(*addr[add],w0=w0,w1=w1,w2=w2)
Stampe:
Name: Billy Bob Doe3 Address: 454 Heartland St, Mobile, AL 00103 phone: 205-123-1232
Name: John Doe2 Address: 123 Main St, Los Angeles, CA 95002 phone: 213-123-1234
Name: John Doe1 Address: 145 Pearl St, La Jolla, CA 92013 phone: 858-123-1233
Ma, dal momento che si hanno i dati in un dizionario indicizzata, è possibile stamparlo come un tavolo invece ordinati per CAP:
# print table header
print '|{0:^{w0}}|{1:^{w1}}|{2:^{w2}}|'.format('Name','Address','Phone',w0=w0+2,w1=w1+2,w2=w2+2)
print '|{0:^{w0}}|{1:^{w1}}|{2:^{w2}}|'.format('----','-------','-----',w0=w0+2,w1=w1+2,w2=w2+2)
# print data sorted by last field of the address - probably a zip code
for add in sorted(addr.keys(),key=lambda x: addr[x][1].split()[-1]):
print '|{0:>{w0}}|{1:>{w1}}|{2:>{w2}}|'.format(*addr[add],w0=w0+2,w1=w1+2,w2=w2+2)
Stampe:
| Name | Address | Phone |
| ---- | ------- | ----- |
| Billy Bob Doe3| 454 Heartland St, Mobile, AL 00103| 205-123-1232|
| John Doe1| 145 Pearl St, La Jolla, CA 92013| 858-123-1233|
| John Doe2| 123 Main St, Los Angeles, CA 95002| 213-123-1234|
Cosa hai provato? – nneonneo
Buona domanda iniziale, @tafiela. Ma non dimenticare di indicare nelle domande successive cosa hai provato a fare. – Yamaneko
L'indirizzo è in realtà solo una riga dopo i due punti? –