我不熟悉字符串解析库;并希望从:
'foo=5 z v xz er bar=" hel o" c z a == "hi" b = "who"'
到这个解析的字典:
{'foo':5, 'bar': ' hel o', 'a': 'hi', b: 'who'}
但我不知道从哪里开始。你可以给我一些处理这种转换的建议吗?
答案 0 :(得分:2)
您可以使用正则表达式。请参阅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个空格(假设“_”是空格)
答案 1 :(得分:0)
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'}