目的是将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 ConfigParser
(https://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 配置文件格式?