[英]Parsing portions of string into dictionary?
我不熟悉字符串解析庫; 並希望從:
'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文檔 。
這樣的東西可以工作:
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)*
表示匹配(?: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'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.