0

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

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

对于这个解析的字典:

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

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

4

2 回答 2

2

你可以使用正则表达式。请参阅python 的正则表达式文档教程的点教程

像这样的东西可以工作:

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 个空格(假装“_”是空格)

于 2013-06-27T20:23:15.037 回答
1

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'}
于 2013-09-15T17:47:48.823 回答