繁体   English   中英

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

[英]Python: Parsing a String to create comma separated values

我有下面的字符串,我想解析此字符串并获取字符串中=之后的值,以逗号分隔。

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']

也许时间戳不是您想要的,所以请尝试以下操作:

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']

您的数据格式不正确,某些值中包含空格,并且某些数据中没有值。 因此,在纯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方式。 它有一个局限性,即假定键不包含空格(使用正则表达式的答案也有此局限性)。

output = []
for token in string.split(' '):
    if '=' in token:
        output.append(token.split('=')[1])
    else:
        output.append(output.pop() + ' ' + token)

print output

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM