在python中将无组织数据转换为可解析格式

时间:2017-12-21 17:34:54

标签: python python-2.7

我有这个代码,它有这个代码的每个元素都有意义。

 PRICING OPTION 11                 TOTAL AMOUNT             40009 INR
ADT                               TAX INCLUDED 
1   UK    933  K  15FEB DEL BOM   1515  1725    TH   320       SRCI0
2   NH    830  S  15FEB BOM NRT   2000  0715 +  TH   788       SRCI0
3   NH    829  V  19FEB NRT BOM   1115  1825    MO   788       VRCI0
4   UK    988  K  19FEB BOM DEL   2045  2300    MO   320       VRCI0
´BOOKª          +TQ                                                      D  R  +8

 PRICING OPTION 12                 TOTAL AMOUNT             40376 INR
ADT                               TAX INCLUDED 
1   NH @ 6431  S  15FEB DEL BOM   1500  1715    TH   73H       SRCI0
2   NH    830  S  15FEB BOM NRT   2000  0715 +  TH   788       SRCI0
3   NH    827  W  19FEB NRT DEL   1715  0005 +  MO   788       WRCI0
´BOOKª          +TQ 

我尝试使用python提取每一行并为每一行分割空格。问题是同一元素的不同行中的空格数可能不同。

除了寻找空格之外,有没有更好的方法从这段代码中提取元素?

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式:

import re
final_data = [list(filter(lambda x:x, re.split('\s+', i))) for i in data.split('\n')][1:-1]

输出:

[['PRICING', 'OPTION', '11', 'TOTAL', 'AMOUNT', '40009', 'INR'], ['ADT', 'TAX', 'INCLUDED'], ['1', 'UK', '933', 'K', '15FEB', 'DEL', 'BOM', '1515', '1725', 'TH', '320', 'SRCI0'], ['2', 'NH', '830', 'S', '15FEB', 'BOM', 'NRT', '2000', '0715', '+', 'TH', '788', 'SRCI0'], ['3', 'NH', '829', 'V', '19FEB', 'NRT', 'BOM', '1115', '1825', 'MO', '788', 'VRCI0'], ['4', 'UK', '988', 'K', '19FEB', 'BOM', 'DEL', '2045', '2300', 'MO', '320', 'VRCI0'], ['´BOOKª', '+TQ', 'D', 'R', '+8'], [], ['PRICING', 'OPTION', '12', 'TOTAL', 'AMOUNT', '40376', 'INR'], ['ADT', 'TAX', 'INCLUDED'], ['1', 'NH', '@', '6431', 'S', '15FEB', 'DEL', 'BOM', '1500', '1715', 'TH', '73H', 'SRCI0'], ['2', 'NH', '830', 'S', '15FEB', 'BOM', 'NRT', '2000', '0715', '+', 'TH', '788', 'SRCI0'], ['3', 'NH', '827', 'W', '19FEB', 'NRT', 'DEL', '1715', '0005', '+', 'MO', '788', 'WRCI0'], ['´BOOKª', '+TQ']]

答案 1 :(得分:1)

您可以将regex拆分用于此目的!

>>> import re
>>> [re.split(' +',line) for line in a.split('\n')] 
[['PRICING', 'OPTION', '11', 'TOTAL', 'AMOUNT', '40009', 'INR'], ['ADT', 'TAX', 'INCLUDED', ''], ['1', 'UK', '933', 'K', '15FEB', 'DEL', 'BOM', '1515', '1725', 'TH', '320', 'SRCI0'], ['2', 'NH', '830', 'S', '15FEB', 'BOM', 'NRT', '2000', '0715', '+', 'TH', '788', 'SRCI0'], ['3', 'NH', '829', 'V', '19FEB', 'NRT', 'BOM', '1115', '1825', 'MO', '788', 'VRCI0'], ['4', 'UK', '988', 'K', '19FEB', 'BOM', 'DEL', '2045', '2300', 'MO', '320', 'VRCI0'], ['´BOOKª', '+TQ', 'D', 'R', '+8'], [''], ['', 'PRICING', 'OPTION', '12', 'TOTAL', 'AMOUNT', '40376', 'INR'], ['ADT', 'TAX', 'INCLUDED', ''], ['1', 'NH', '@', '6431', 'S', '15FEB', 'DEL', 'BOM', '1500', '1715', 'TH', '73H', 'SRCI0'], ['2', 'NH', '830', 'S', '15FEB', 'BOM', 'NRT', '2000', '0715', '+', 'TH', '788', 'SRCI0'], ['3', 'NH', '827', 'W', '19FEB', 'NRT', 'DEL', '1715', '0005', '+', 'MO', '788', 'WRCI0'], ['´BOOKª', '+TQ', '']]