【问题标题】:Parsing portions of string into dictionary?将部分字符串解析成字典?
【发布时间】:2013-06-27 18:52:14
【问题描述】:

我不熟悉字符串解析库;并想从:

'foo=5 z v xz er bar=" hel o" c z a == "hi" b = "who"'

到这个已解析的字典:

{'foo':5, 'bar': ' hel o', 'a': 'hi', b: 'who'}

但我不知道从哪里开始。您能给我一些处理这种转换的建议吗?

【问题讨论】:

  • 所以v、xz、er 等等没有等号的东西就直接掉在地上了吗?另外,Python 的起点大概是shlex。
  • 没有= 或== 的所有内容都不应出现在字典中。 (我在一个单独的阶段处理它们)

标签: python parsing grammar text-parsing string-parsing


【解决方案1】:

你可以使用正则表达式。请参阅python's documentation on regex 或tutorial's point tutorial。

这样的东西可以工作:

import re

regex = re.compile(r"(\w+ ?=+ ?\d+|\w+ ?=+ ?\"(?: *\w*)*\")")

#your example string:
s = 'foo=5 z v xz er bar=" hel o" c z a == "hi" b = "who"'

matches = regex.findall(s)

dict1 = {}
for m in matches:
    elems = m.split("=")
    #elems[0] = key
    #elems[len(elems)-1] = value, to account for the case of multiple ='s

    try:
        #see if the element is a number
        dict1[str(elems[0])] = int(elems[len(elems) - 1]) 

    except:
        #if type casting didn't work, just store it as a string
        dict1[str(elems[0])] = elems[len(elems) - 1] 

下面是正则表达式的分解:

(\w+ ?=+ ?\d+|\w+ ?=+ ?\"(?: *\w*)*\")

\w+ 表示一个或多个字母数字字符。

\d+ 表示一位或多位数字。

(?:regex)* 表示匹配 0 个或多个正则表达式副本而不为其分配组 #。

(regex1|regex2) 表示查找与regex1 匹配或与regex2 匹配的字符串。

\" 是引号的转义序列。

=+ 表示匹配一个或多个“=”符号

_? 表示匹配0或1个空格(假装“_”是空格)

【讨论】:

    【解决方案2】:

    Pyparsing 是一个解析库,可让您一次构建匹配表达式。

    from pyparsing import Word, alphas, alphanums, nums, oneOf, quotedString, removeQuotes
    
    identifier = Word(alphas, alphanums)
    integer = Word(nums).setParseAction(lambda t: int(t[0]))
    value = integer | quotedString.setParseAction(removeQuotes)
    
    # equals could be '==' or '='
    # (suppress it so it does not get included in the resulting tokens)
    EQ = oneOf("= ==").suppress()
    
    # define the expression for an assignment
    assign = identifier + EQ + value
    

    这是应用此解析器的代码

    # search sample string for matching assignments
    s = 'foo=5 z v xz er bar=" hel o" c z a == "hi" b = "who"'
    assignments = assign.searchString(s)
    dd = {}
    for k,v in assignments:
        dd[k] = v
    
    # or more simply
    #dd = dict(assignments.asList())
    
    print dd
    

    给予:

    {'a': 'hi', 'b': 'who', 'foo': 5, 'bar': ' hel o'}
    

    【讨论】:

      猜你喜欢
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多