[英]Extract data from within parenthesis in python
I know there are many questions with the same title. 我知道有很多标题相同的问题。 My situation is a little different. 我的情况有些不同。 I have a string like: 我有一个像这样的字符串:
"Cat(Money(8)Points(80)Friends(Online(0)Offline(8)Total(8)))Mouse(Money(10)Points(10000)Friends(Online(10)Offline(80)Total(90)))"
(Notice that there are parenthesis nested inside another) (注意,括号内嵌套了另一个括号)
and I need to parse it into nested dictionaries like for example: 我需要将其解析为嵌套字典,例如:
d["Cat"]["Money"] == 8
d["Cat"]["Points"] = 80
d["Mouse"]["Friends"]["Online"] == 10
and so on. 等等。 I would like to do this without libraries and regex. 我想在没有库和正则表达式的情况下执行此操作。 If you choose to use these, please explain the code in great detail. 如果您选择使用这些代码,请详细解释代码。 Thanks in advance! 提前致谢!
Edit: 编辑:
Although this code will not make any sense, this is what I have so far: 尽管这段代码没有任何意义,但这是我到目前为止的内容:
o_str = "Jake(Money(8)Points(80)Friends(Online(0)Offline(8)Total(8)))Mouse(Money(10)Points(10000)Friends(Online(10)Offline(80)Total(90)))"
spl = o_str.split("(")
def reverseIndex(str1, str2):
try:
return len(str1) - str1.rindex(str2)
except Exception:
return len(str1)
def app(arr,end):
new_arr = []
for i in range(0,len(arr)):
if i < len(arr)-1:
new_arr.append(arr[i]+end)
else:
new_arr.append(arr[i])
return new_arr
spl = app(spl,"(")
ends = []
end_words = []
op = 0
cl = 0
for i in range(0,len(spl)):
print i
cl += spl[i].count(")")
op += 1
if cl == op-1:
ends.append(i)
end_words.append(spl[i])
#break
print op
print cl
print
print end_words
The end words are the sections at the beginning of each statement. 结束语是每个语句开头的部分。 I plan on using recursive to do the rest. 我计划使用递归来完成其余的工作。
Now that was interesting. 现在,这很有趣。 You really nerd-sniped me on this one... 你真的很讨厌我这个...
def parse(tokens):
""" take iterator of tokens, parse to dictionary or atom """
dictionary = {}
# iterate tokens...
for token in tokens:
if token == ")" or next(tokens) == ")":
# token is ')' -> end of dict; next is ')' -> 'leaf'
break
# add sub-parse to dictionary
dictionary[token] = parse(tokens)
# return dict, if non-empty, else token
return dictionary or int(token)
Setup and demo: 设置和演示:
>>> s = "Cat(Money(8)Points(80)Friends(Online(0)Offline(8)Total(8)))Mouse(Money(10)Points(10000)Friends(Online(10)Offline(80)Total(90)))"
>>> tokens = iter(s.replace("(", " ( ").replace(")", " ) ").split())
>>> pprint(parse(tokens))
{'Cat': {'Friends': {'Offline': 8, 'Online': 0, 'Total': 8},
'Money': 8,
'Points': 80},
'Mouse': {'Friends': {'Offline': 80, 'Online': 10, 'Total': 90},
'Money': 10,
'Points': 10000}}
Alternatively, you could also use a series of string replacements to turn that string into an actual Python dictionary string and then evaluate that, eg like this: 另外,您还可以使用一系列字符串替换将其转换为实际的Python字典字符串,然后对其进行求值,例如:
as_dict = eval("{'" + s.replace(")", "'}, ")
.replace("(", "': {'")
.replace(", ", ", '")
.replace(", ''", "")[:-3] + "}")
This will wrap the 'leafs' in singleton sets of strings, eg {'8'}
instead of 8
, but this should be easy to fix in a post-processing step. 这会将'leaf'包装在单例字符串集中,例如{'8'}
而不是8
,但这在后处理步骤中应该很容易解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.