我想把这个unicode字符串列表解析成一个表:
[u'$760,507,625 (USA) (18 November 2010)', u'$760,505,847 (USA) (14 November 2010)', u'$760,462,559 (USA) (7 November 2010)', u'$760,410,799 (USA) (31 October 2010)',
所以我想要的结果是:
[[760507625, 11, 18, 2010, 'USA'],
[760505847, 11, 7, 2010, 'USA'],
....
]
如您所见,格式为[金钱,月,日,年,国家]
也许你可以提供可以解决这个问题的工具。 我让我清楚了吗?非常感谢!
答案 0 :(得分:1)
我要处理的常用方法是使用正则表达式从每行中取出字段,然后为每个字段添加一行或两行以将其转换为所需格式。这不是万无一失的 - 例如,如果一行有一个错误拼写的月份的条目,它就会崩溃 - 但这对于大多数临时任务来说都足够了。
#!/usr/bin/env python2.7
import re
data = [u'$760,507,625 (USA) (18 November 2010)',
u'$760,505,847 (USA) (14 November 2010)',
u'$760,462,559 (USA) (7 November 2010)',
u'$760,410,799 (USA) (31 October 2010)',
'blah']
RE_DATA = re.compile(r'^\$([0-9,]+) \(([A-Z]+)\) \(([0-9]+) ([A-Za-z]+) ([0-9]+)\)$')
MONTHS = {
'January': 1,
'February': 2,
'March': 3,
'April': 4,
'May': 5,
'June': 6,
'July': 7,
'August': 8,
'September': 9,
'October': 10,
'November': 11,
'December': 12
}
for entry in data:
match = RE_DATA.match(entry)
if match is None:
print 'Error! %r did not match pattern' % entry
continue
amount, country, day, month, year = match.groups()
amount = int(amount.replace(',', ''))
country = str(country)
day = int(day)
month = MONTHS[month]
year = int(year)
print [amount, month, day, year, country]
打印:
[760507625, 11, 18, 2010, 'USA']
[760505847, 11, 14, 2010, 'USA']
[760462559, 11, 7, 2010, 'USA']
[760410799, 10, 31, 2010, 'USA']
Error! 'blah' did not match pattern