これは、独自のパーサーを処理する必要があります。私はまだそれをConfigParser
オブジェクトにドロップしますが、それだけで将来もっと簡単に使用できるようになります。 configparser.ConfigParser
はのようにほとんどする必要があります。私はあなたの質問の終わり近くに言及としてconfig["SomeHeader"]["foo"] == ["bar", "baz"]
として
[SomeHeader]
foo = bar
foo = baz
を治療するためにそれを伝えるためにどのような方法を認識していませんよ。
あなたのような何かを試みることができる:これは、ようになります
def is_section_header(text):
# what makes a section header? To me it's a word enclosed by
# square brackets.
match = re.match(r"\[([^\]]+)\]", text)
if match:
return match.group(1)
def get_option_value_tuple(line):
"""Returns a tuple of (option, comma-separated values as a string)"""
option, *values = line.split(" ")
return (option, ", ".join(values))
def parse(filename):
config = configparser.ConfigParser()
cursection = None
with open(filename) as inifile:
for line in inifile:
sectionheader = is_section_header(line)
if sectionheader:
cursection = sectionheader
try:
config.add_section(sectionheader)
except configparser.DuplicateSectionError:
# This section already exists!
# how should you handle this?
continue # ignore for now
else:
option, values = get_option_value_tuple(line.strip())
if config.has_option(cursection, option):
config[cursection][option] += (", " + values)
else:
config[cursection][option] = values
return config
を:
[SomeHeader]
foo bar baz
foo spam eggs
bar baz
はこれを手動で解析
[SomeHeader]
foo = bar, baz, spam, eggs
bar = baz
の標準解析と同じように解析しても、あまりにもではありませんハード - あなたのパラメータ名の中に空白が含まれていない限り、 'line.split( '')'のようなもので逃げることができます。 –
'newline = line.split( '')[0] +" = "+"、 ".join(line.split( '')[1:]' – handle
あなたのiniから通常のiniに変換するだけです。単純に見えますが、そのフォーマットに複雑さが潜んでいる可能性があります。同じヘッダーが2回表示された場合は、追加または上書きしますか?置換変数を許可しますか?コメントを付けることができますか?どのように表現されていますか?Confiig構文解析は暗い芸術です! – tdelaney