正则表达式匹配并进入python列表

2024-09-30 01:24:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我将以下内容保存为变量中的字符串:

window.dataLayer=[{"articleCondition":"New","categoryNr":"12345","sellerCustomerNr":"88888888","articleStatus":"Open"}]

如何提取每个元素的值? 我们的目标是这样:

articleCondition = 'new'

categoryNr = '12345'

。。。你知道吗


Tags: 字符串元素目标newopenwindowdatalayerarticlestatus
3条回答

使用json。您的字符串是:

>>> s = 'window.dataLayer=[{"articleCondition":"New","categoryNr":"12345","sellerCustomerNr":"88888888","articleStatus":"Open"}]'

您可以通过拆分获得=的右侧:

>>> s.split('=')[1]
'[{"articleCondition":"New","categoryNr":"12345","sellerCustomerNr":"88888888","articleStatus":"Open"}]'

然后用json模块解析它:

>>> import json
>>> t = json.loads(s.split('=')[1])
>>> t[0]['articleCondition']
'New'

请注意,这是因为在RHS中有双引号。JSON中不允许使用单引号。你知道吗

你有一本词典的目录。使用字典键获取值。你知道吗

例如:

dataLayer=[{"articleCondition":"New","categoryNr":"12345","sellerCustomerNr":"88888888","articleStatus":"Open"}]
print(dataLayer[0]["articleCondition"])
print(dataLayer[0]["categoryNr"])

输出:

New
12345

在python中,有许多方法可以从字符串中获取值,可以使用regex、python eval函数,甚至还有更多我可能不知道的方法。你知道吗

方法1

value = 'window.dataLayer=[{"articleCondition":"New","categoryNr":"12345","sellerCustomerNr":"88888888","articleStatus":"Open"}]'
value = value.split('=')[1]
data = eval(value)[0]
articleCondition = data['articleCondition']

方法2

使用regex

import re
re.findall('"articleCondition":"(\w*)"',value)

对于regex,您可以更具创造性地创建一个通用模式。你知道吗

相关问题 更多 >

    热门问题