Skip to content Skip to sidebar Skip to footer

Python: Parse One String Into Multiple Variables?

I am pretty sure that there is a function for this, but I been searching for a while, so decided to simply ask SO instead. I am writing a Python script that parses and analyzes tex

Solution 1:

This uses the remarkably useful dateutil library to make date parsing easier - you can pip install python-dateutil or easy_install python-dateutil it. Split the data on the : and the - to get message and sender, then process the date text to get a datetime object where you can access its various attributes to get the components required, eg:

from dateutil.parser import parse

s = 'Apr 4, 19:20 - Lee White: Hello world!'
fst, _, msg = s.rpartition(': ')date, _, name = fst.partition(' - ')date = parse(date)
name, msg, date.year, date.month, date.day, date.hour, date.minute
# ('Lee White', 'Hello world!', 2015, 4, 4, 19, 20)

Solution 2:

Method strptime() may be used:

import time

strn = 'Apr 4, 19:20 - Lee White: Hello world!'

try:
    date = time.strptime(strn.split(' - ')[0],'%b %d, %Y, %H:%M')
    year = date.tm_year
except ValueError:
    date = time.strptime(strn.split(' - ')[0],'%b %d, %H:%M')
    year = time.asctime().split()[-1]

sender = strn.split('- ')[1].split(':')[0]
text = strn.split(': ')[1]

date.tm_mon, date.tm_mday, year, date.tm_hour, date.tm_min, sender, text

Post a Comment for "Python: Parse One String Into Multiple Variables?"