1

目的是将org.apache.commons.configuration文件更改为 pythonable configparser 文件

我有一个这样的 Java Apache 配置文件(完整文件是http://pastebin.com/Wz2T2KV9):

##############################
# BABELNET-RELATED PROPERTIES
##############################

include = babelnet.var.properties

babelnet.fullFile = ${babelnet.dir}/babel-synsets-full.txt
babelnet.dictFile = ${babelnet.dir}/babel-synsets-lexicon.txt
babelnet.glossFile = ${babelnet.dir}/babel-synsets-gloss.txt
babelnet.relFile = ${babelnet.dir}/babel-synsets-relations.txt
babelnet.mapFile = ${babelnet.dir}/babel-synsets-mapping.txt


#################
# DB BABELCO
#################

babelco.windowRadius=20

babelco.db.user=root
babelco.db.password=

我想将它转换成python ConfigParserhttps://docs.python.org/2/library/configparser.html)可以解析的文件,即

[BABELNET-RELATED PROPERTIES]

include = babelnet.var.properties

babelnet.fullFile = ${babelnet.dir}/babel-synsets-full.txt
babelnet.dictFile = ${babelnet.dir}/babel-synsets-lexicon.txt
babelnet.glossFile = ${babelnet.dir}/babel-synsets-gloss.txt
babelnet.relFile = ${babelnet.dir}/babel-synsets-relations.txt
babelnet.mapFile = ${babelnet.dir}/babel-synsets-mapping.txt


[DB BABELCO]
babelco.windowRadius=20

babelco.db.user=root
babelco.db.password=

我试过这个,但它给了我错误的输出:

fin = open('configfile', 'r')

sections = {}
headers = []
start_header = False
prev = ""
this_header = ""
this_section = []


for line in fin:
    line = line.strip()
    if line.startswith('#') and line.endswith('#') and start_header == False:
        start_header = True
        sections[this_header] = this_section
        headers.append(this_header)
        this_header = ""
        this_section = []
        prev = ""
        continue
    if line.startswith('#') and not line.endswith('#') and start_header == True:
        this_header = line[2:].strip()
        continue
    if line.startswith('#') and line.endswith('#') and this_header:
        start_header = False
        continue
    this_section.append(line.strip())

for h in headers:
    print '[' + h + ']'
    for line in sections[h]:
        print line

有没有更简单的方法将 Java Apache commons 配置文件格式转换为 python 配置文件格式?

4

1 回答 1

1

试试这个(我使用了 Python 2.7)——这假设输入文件格式很好(编辑以处理空注释行)。如果您想容忍格式错误的配置,则必须添加额外的错误处理。

import re

fin = open('configfile', 'r')

for line in fin:
    line = line.strip()
    if re.search(r'^\s*##+\s*$', line):
        match = re.search(r'^\s*#\s*(.*?)\s*$', fin.next().strip())
        print "[%s]" % match.group(1)
        # Absorb the next line, which should just be #s
        fin.next()
        continue
    else:
        print line
于 2014-11-28T13:07:06.733 回答