【问题标题】:regex matching and get into a python list正则表达式匹配并进入 python 列表
【发布时间】:2018-10-09 01:28:45
【问题描述】:

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

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

如何提取每个元素的值? 目标是拥有这样的东西:

articleCondition = 'new'

categoryNr = '12345'

...

【问题讨论】:

    标签: python regex list variables beautifulsoup


    【解决方案1】:

    在python中有很多方法可以从字符串中获取值,你可以使用regex、Pythoneval函数以及更多我可能不知道的方法。

    方法一

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

    方法二

    使用regex

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

    对于regex,您可以更有创意地制作通用模式。

    【讨论】:

    • 根据您的目标,尽管这可行,但我会远离 eval() 函数! -- stackoverflow.com/questions/1832940/…
    • 非常感谢。我发现正则表达式版本对我来说最容易理解和实现。
    【解决方案2】:

    你有一个字典列表。使用字典键获取值。

    例如:

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

    输出:

    New
    12345
    

    【讨论】:

    • 我认为 OP 有一个类似 string = 'window.dataLayer=[{"articleCondition":"New","categoryNr":"12345","sellerCustomerNr":"88888888","articleStatus":"Open"}]' 的字符串。
    【解决方案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 中不允许使用单引号。

    【讨论】:

      猜你喜欢
      • 2012-04-23
      • 2016-07-01
      • 2013-09-22
      • 2018-01-08
      • 1970-01-01
      • 2022-12-11
      • 2014-03-30
      • 2022-08-10
      • 2015-03-26
      相关资源
      最近更新 更多