![](/img/trans.png)
[英]Keep track of how many times a recursive function has been called in Python
[英]Python recursive function called too many times
這是這個問題的后續: Python parse text file into nested dictionaries
我最初接受了建議使用正則表達式格式化輸入的答案,但是在仔細查看輸入后,仍然存在一些我無法使用建議的正則表達式處理的問題。
所以我回到遞歸地將這些行解析成字典。
到目前為止我所擁有的是:
def parseToDictionary(input):
key = ''
value = ''
result = {}
if input[0].startswith('{'): # remove {
del input[0]
result.clear() # clear the dict for each recursion
for idx, line in enumerate(input):
line = line.rstrip() # remove trailing returns
if line.startswith('['):
key = line
value = parseToDictionary(input[idx+1:]) # parse the next level
elif line.startswith('}'): # reached the end of a block
return result
else:
elements = line.split('\t')
key = elements[0]
if len(elements) > 1:
value = elements[1]
else:
value = 'Not defined' # some keys may not have a value, so set a generic value here
if key:
result[key] = value
return result
這是一個示例(非常簡化!)輸入:
[HEADER1]
{
key1 value
key2 long value, with a comma
[HEADER2]
{
key 1234
emptykey
}
}
輸出是:
'[HEADER2]':
{
'emptykey': 'Not defined',
'key': '1234'
},
'key2': 'long value, with a comma',
'key1': 'value',
'[HEADER1]':
{
'emptykey': 'Not defined',
'key2': 'long value, with a comma',
'key1': 'value',
'key': '1234',
'[HEADER2]':
{
'emptykey': 'Not defined',
'key': '1234'
}
},
'emptykey': 'Not defined',
'key': '1234'
}
但它應該是:
'[HEADER1]':
{
'key1': 'value',
'key2': 'long value, with a comma',
'[HEADER2]':
{
'emptykey': 'Not defined',
'key': '1234'
}
}
因此,以[
開頭的每一行都是下一個塊的鍵。 每個塊內部都有多個鍵值對,也可能有另一個嵌套級別。 出錯的是某些塊被多次解析,我無法弄清楚哪里出錯了。
輸入參數是mydatafile.split('\\n')
誰能幫幫我?
您必須跳過在小節中處理的行:
def parse_to_dictionary(lines):
def parse_block(lines):
contents = {}
if next(lines).strip() != '{':
raise AssertionError("'{' expected")
for line in lines:
line = line.strip()
if line == '}':
return contents
elif line[0] == '[':
contents[line] = parse_block(lines)
else:
parts = line.split('\t', 1)
contents[parts[0]] = None if len(parts) == 1 else parts[1]
lines = iter(lines)
key = next(lines)
if key[0] != '[':
raise AssertionError("format error")
return {key: parse_block(lines)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.