【发布时间】:2014-09-26 11:56:13
【问题描述】:
我已尝试了解如何执行此操作(google、SO 等),但我可能使用了错误的关键字...
基本上我逐行遍历文件,如果我点击一个关键字,我想将它添加到字典中作为它的键,但是,我想将它的值添加为初始字典的字典,然后任何后续的点击作为它的孩子(等等),除非我点击一个接近的字符,它会在字典中上升一个级别。
示例文件:
def myitem {
def aSubItem {
abc
}
def anotherSubItem {
hi!
hows you?
}
}
所以我会得到这样的字典:
mydict = {
"myitem" : {
"aSubItem" : { "abc" },
"anotherSubItem" : { "hi!", "hows you?" }
}
}
基本上,我正在寻找一种可以存储当前深度(或 dict 访问)的方法,例如,您可以通过执行 mydict['myitem']['aSubItem'] 来访问“abc”,但我想要能够存储我的深度以防有人在该块中添加了一些东西......所以就像:
curLevel = ['myitem']['aSubItem']
然后我可以告诉 mydict 访问 curLevel,然后当块完成时(点击 } ),我可以告诉它上升“一级”到
curLevel = ['myitem']
====================
我知道我可以使用
curLevel = mydict
这将让我使用 curLevel 访问 myDic... 这可以很好地进入字典级别......
但是,我要怎么上去呢? 即如果我有:
curLevel = mydict['myitem']['aSubItem']
我该怎么去
curLevel = mydict['myitem']
=====================
这是一些示例代码,因为每个人都喜欢示例代码:P
这正在进入字典,我只是不知道如何让它恢复
import os
import re
# file location
fle = "myfilelocation"
# read file contents
fh = open(fle, 'r')
content = fh.readlines()
# The dictionary to hold the structure
structure = {}
# reference to structure that we will use in the loop
cur = structure
# loop through file lines
for line in content:
# Match our starting def line ( def ___ { )
st = re.match(r'\s*Def\s([^{\s]+)', line, re.IGNORECASE)
if st:
cur[st.group(1)] = {}
cur = cur[st.group(1)]
# Match the close of a block ( } )
ed = re.match(r'\s*}\s*', line)
if ed:
# ??? How do I tell it to go up one dict level??
None
# If its neither, add to current level of array
# Don't mind the inefficiency here, I'll be improving it later
if not st and not ed and not re.match(r'\s*{\s*$', line) and not re.match(r'\s*$', line):
# Not implemented yet
None
print(structure)
目前上述示例代码的输出类似于
mydict = {
"myitem" : {
"aSubItem" : {
"anotherSubItem" : {}
}
}
}
}
如果需要更多信息,很乐意提供:)
(是的,我知道我可能会使用解析器......但我对它们中的任何一个都完全没有运气......此外,从头开始写东西是一个很好的练习练习 xD)
【问题讨论】:
-
“示例文件”是否正确?我希望在 myitem 之前有一个“def”。
-
另外,将值“abc”、“hi!”放在一起是没有意义的。或“你好吗?”在字典里。
-
可能会在实际代码中使用一个列表,我主要是想弄清楚如何在循环中向上移动字典(根据问题):) .. 感谢您注意到这一点。跨度>
-
考虑编写一个递归解析器。每当它遇到一个新的 def 块时,它就会组合内容并返回一个 dict。内部 def 块通过递归调用解析器并将其返回值注入外部字典来处理。
标签: python loops python-3.x dictionary reference