我不熟悉字符串解析库;并想从去:将字符串的部分解析为字典?
'foo=5 z v xz er bar=" hel o" c z a == "hi" b = "who"'
对此解析词典:
{'foo':5, 'bar': ' hel o', 'a': 'hi', b: 'who'}
但我不知道从哪里开始。你能否给我一些处理这种转换的建议?
我不熟悉字符串解析库;并想从去:将字符串的部分解析为字典?
'foo=5 z v xz er bar=" hel o" c z a == "hi" b = "who"'
对此解析词典:
{'foo':5, 'bar': ' hel o', 'a': 'hi', b: 'who'}
但我不知道从哪里开始。你能否给我一些处理这种转换的建议?
您可以使用正则表达式。见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位(假装“_”为空格)
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'}
所以'v','xz','er'等东西,不有一个等号只是落在地板上?另外,Python开始的地方可能是[shlex](http://docs.python.org/2/library/shlex.html)。 – zwol
没有'='或'=='的所有内容都不应该出现在字典中。 (我正在分开处理它们) –