我需要解析包含應用程序配置的文本文件。文件內容的格式如下:以遞歸方式處理文本的Python方法
參數1 = VAL1
參數2 =值2
hash.param3 = {
subparam3 = subval3
subparam4 = subval4
}
...
我想將它存儲在字典中:
self.values = {'param1': 'value1', 'param2': 'value2',
'param3':{'subparam3':'subvalue3', 'subparam4': 'subvalue4'}
我有這個工作正常使用全局變量之間共享的一些功能,但想再次嘗試使用類作爲學習練習,我已經做了,但它仍然感覺笨重。
這是我目前有:
class Cfg(object):
def __init__(self, abs_path):
self._text = iter(open(abs_path, 'r').readlines())
self.values = {}
self._parse_cfg(self.values)
@property
def next_line(self):
"""Get next non-blank, non-comment line."""
while True:
nl = next(self._text).strip()
if nl and not nl.startswith('#'):
return nl
def _parse_cfg(self, dic):
while True:
try:
line = self.next_line
# closing brace signals end of sub dict
if line.startswith('}'):
break
# Look for param with hash prefix, which signifies a new subdict
elif re.match(hash_rgx, line):
m = re.match(hash_rgx, line)
# Add new hash dict
dic[m.group('hash')] = {}
# collect keys/values for subdict until closing brace found
self._parse_cfg(dic[m.group('hash')])
# Look for normal key=value pair
elif re.match(val_rgx, line):
m = re.match(val_rgx, line)
dic[m.group('key')] = m.group('val')
else:
raise ValueError('line ignored *' + str(line) + '*')
except StopIteration:
break
我正在尋找如何做到這一點在一個更清潔,更Python的方式提出建議。
謝謝!
看起來像這屬於http://codereview.stackexchange.com –
遞歸不是pythonic。 http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html – saarrrr
當next_line(self)方法到達輸入結尾時,它會做什麼? –