这里的大多数解决方案只是重新格式化您正在阅读的文件中的数据。也许这就是你想要的。
如果您确实要解析数据,请将其放入数据结构中。
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))]
现在您可以自由排序、更改格式、放入数据库等。
这将使用该数据打印您的格式,并排序:
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)
印刷:
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
这是按姓氏排序的,字典键中使用的名字。
现在按区号排序打印它:
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)
印刷:
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
但是,由于您在索引字典中有数据,您可以将其打印为表格,而不是按邮政编码排序:
# 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)
印刷:
| 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|