Python:解析字符串以创建逗号分隔的值

Python:解析字符串以创建逗号分隔的值,python,python-2.7,Python,Python 2.7,我有如下字符串,我想解析这个字符串,并将字符串中=后面的值作为逗号分隔的值 string = "TimeStamp=[2017-03-07 00:22:12.697Z] RequestUri=https://google.com SessionId={null} UserId=8273527 VisitorId= UserAgent=\"Abc Proxy\" SystemType=Connect ClientIp=140.11.135.123 IsTestSystem=False" 预期产出

我有如下字符串,我想解析这个字符串,并将字符串中
=
后面的值作为逗号分隔的值

string = "TimeStamp=[2017-03-07 00:22:12.697Z] RequestUri=https://google.com SessionId={null} UserId=8273527 VisitorId= UserAgent=\"Abc Proxy\" SystemType=Connect ClientIp=140.11.135.123 IsTestSystem=False"
预期产出:

'[2017-03-07 00:22:12.697Z]','https://google.com','{null}','8273527','','Abc Proxy','Connect','140.11.135.123','False'

非常感谢您的帮助。

我建议您尝试使用
str.split
方法:

s = "TimeStamp=[2017-03-07 00:22:12.697Z] RequestUri=https://google.com SessionId={null} UserId=8273527 VisitorId= UserAgent=\"Abc Proxy\" SystemType=Connect ClientIp=140.11.135.123 IsTestSystem=False"
print [i.split("=")[-1] for i in s.split()]
输出:

['[2017-03-07', '00:22:12.697Z]', 'https://google.com', '{null}', '8273527', '', '"Abc', 'Proxy"', 'Connect', '140.11.135.123', 'False']
['[2017-03-07 00:22:12.697Z]', 'https://google.com', '{null}', '8273527', '', '"Abc', 'Proxy"', 'Connect', '140.11.135.123', 'False']
可能时间戳不是您想要的,请尝试以下操作:

first_split = s.split("]", 1)
print ["["+first_split[0].split("[")[-1]+"]"] + [i.split("=")[-1] for i in first_split[1].split()]
输出:

['[2017-03-07', '00:22:12.697Z]', 'https://google.com', '{null}', '8273527', '', '"Abc', 'Proxy"', 'Connect', '140.11.135.123', 'False']
['[2017-03-07 00:22:12.697Z]', 'https://google.com', '{null}', '8273527', '', '"Abc', 'Proxy"', 'Connect', '140.11.135.123', 'False']

数据的格式不是很好,有些值中有空格,有些数据没有值。正因为如此,在纯python中并不容易,所以我将使用
re

>>> import re
>>> re.split(r'\w+\=', string)
['', '[2017-03-07 00:22:12.697Z] ', 'https://google.com ', '{null} ', '8273527 ', ' ', '"Abc Proxy" ', 'Connect ', '140.11.135.123 ', 'False']
您可以通过列表理解添加空字符串检查:

>>> [x.strip() for x in re.split(r'\w+\=', string) if x.strip()]
['[2017-03-07 00:22:12.697Z]', 'https://google.com', '{null}', '8273527', '"Abc Proxy"', 'Connect', '140.11.135.123', 'False']

纯Python方式。它有一个限制,即它假设键不包含空格(使用regex的答案也有这个限制)


您可以从
字符串开始。拆分(“=”
。为什么
标记。如果您可以在标记中执行
如果“=”
,则查找(“=”
)?确实!我最近才学会Python。谢谢你的建议。我修改了密码。