Reputation: 259
I wan to parser this unicode string list into a table:
[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)',
So the result I want is:
[[760507625, 11, 18, 2010, 'USA'],
[760505847, 11, 7, 2010, 'USA'],
....
]
As you can see, the format will be [money, month, day, year, country]
Maybe you can provide me the tools which can handle this problem. Am I making me clear? Thanks so much!
Upvotes: 0
Views: 67
Reputation: 34873
The usual way I would handle this would be with a regular expression to grab the fields out of each line, then a line or two for each field to convert it to the desired format. This isn’t foolproof—it’ll crash if a line has an entry with a mis-spelled month, for example—but it’s enough for most ad-hoc tasks.
#!/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]
Prints:
[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
Upvotes: 1