gpt4 book ai didi

python - 使用python将未格式化的字符串解析为字典

转载 作者:行者123 更新时间:2023-12-04 06:38:52 24 4
gpt4 key购买 nike

我有以下字符串。

DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) Key: a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO

我需要创建字典所以它会像
{
"DATE": "12242010",
"Key Type": "Nod32 Anti-Vir (30d trial)",
"Key": "a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO"
}

问题是字符串未格式化
DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) 
  • 键类型前的日期后没有空格
  • 对 key 进行一些验证也会很好,例如,如果每个 key 框中有 5 个字符和框数

  • 我是 python 的初学者,而且是正则表达式。
    非常感谢。

    这是我的代码。我正在从 xpath 获取字符串。
    为什么我不能在正则表达式中使用它?
    import re
    import lxml.html as my_lxml_hmtl
    tree = my_lxml_hmtl.parse("test.html")
    text = tree.xpath("string(//*[contains(text(),'DATE')])")
    # this works
    print re.match('DATE:\s+([0-9]{8})\s*Key Type:\s+(.+)\s+Key:\s+((?:[^-]{5}(?:-[^-]{5})*))', 'DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) Key: a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO').groups()

    # and this doesn't work, why?
    ss = str(text)
    # print ss gives the same string which worked in re fabove
    print re.match('DATE:\s+([0-9]{8})\s*Key Type:\s+(.+)\s+Key:\s+((?:[^-]{5}(?:-[^-]{5})*))', ss).groups()

    当我尝试使用 text 或 str(text) 而不是
    '日期:12242010 key 类型:Nod32 Anti-Vir(30天试用) key :a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO'
    我收到一个错误
    AttributeError: 'NoneType' 对象没有属性 'groups'

    这里有什么问题?

    最佳答案

    >>> import re
    >>> regex = re.compile(r"DATE: (\d+)Key Type: (.*?) Key: ((?:\w{5}-){5}\w{5})")
    >>> match = regex.match("DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) Key: a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO")
    >>> mydict = {"DATE": match.group(1),
    ... "Key Type": match.group(2),
    ... "Key": match.group(3)}
    >>> mydict
    {'DATE': '12242010', 'Key': 'a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO', 'Key Type': '
    Nod32 Anti-Vir (30d trial)'}
    >>>

    正则表达式 DATE: (\d+)Key Type: (.*?) Key: ((?:\w{5}-){5}\w{5})匹配日期(仅限数字)和 key 类型(任何字符);那么它匹配一个键,如果它包含六组,每组五个字母数字字符,用破折号分隔。

    关于python - 使用python将未格式化的字符串解析为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4525632/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com