开发者

how to extract values of different field from the string in python

I am newbie in python, i have to extract values from a string: str='x:10 y:12 time : 01/01/2010 11开发者_JAVA技巧:55:55'

now i have to create a dictionary in which value is stored in such a way that: x=10

y=12

time=01/01/2010 11:55:55

Please let me know how to do this?


Have you tried anything yet?
If not, here are some ideas...

Using the built-in string manipulation tools
For x and y:

>>> s = 'x:10 y:12 time : 01/01/2010 11:55:55'
>>> [pair.split(':') for pair in s.split(' ',2)[0:2]]
[['x', '10'], ['y', '12']]

and let's say that you then assigned that to a variable:

>>> lol = [x.split(':') for x in s.split(' ',2)[0:2]]
>>> d = {}
>>> for i,j in lol:
...   d[i] = int(j)
... 
>>> d
{'y': 12, 'x': 10}

For time maybe you can start like this:

>>> [term.strip() for term in s.split(' ',2)[-1].split(':',1)]
['time', '01/01/2010 11:55:55']

Regular expressions

>>> import re
>>> re.findall('(\w+):(\d+)',s)[0:2]
[('x', '10'), ('y', '12')]

and then I'd probably just use strptime() for the final datetime portion:

>>> from datetime import datetime
>>> datetime.strptime([term.strip() 
                      for term in 
                      s.split(' ',2)[-1].split(':',1)][1], '%m/%d/%Y %H:%M:%S')
datetime.datetime(2010, 1, 1, 11, 55, 55)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜