一直没找到Python好用的解析properties的代码,前一阵子写python工程的时候,顺便写了一个.已打包到pypi 可用pip install pyconfiganalysis进行安装.下面是源代码:
#coding:utf-8
import re,os
from functools import reduce
class ConfigAnalysis():
def __init__(self):
self.__update_log = {}
self.__add_log = {}
self.__config = {}
self.__configfilename = None
def __validitycheck(self,lines,configfilename):
for line_number in range(len(lines)):
if (not re.match(r'^#', lines[line_number])) and (not re.match(r'^(\r\n|\r|\n)',lines[line_number])) and (not re.match(r'^[a-zA-Z0-9](\w|\.| |\t)*\=( |\t)*(\S|.)*$', lines[line_number])):
raise SyntaxError("The configuration file (%s) have SyntaxError(%s) in line %s"%(configfilename,lines[line_number],line_number+1))
def __analysisfile(self,configfilename):
with open(configfilename,'r') as Contents:
lines = Contents.readlines()
self.__validitycheck(lines,configfilename)
return [re.match(r'^[a-zA-Z0-9](\w|\.| |\t)*\=( |\t)*(\S|.)*$', line).group() for line in lines if re.match(r'^[a-zA-Z0-9](\w|\.| |\t)*\=( |\t)*(\S|.)*$', line)]
def __analysislines(self,vaild_lines)