xls5-解析properties文件,在python中基本没有遇到

https://www.runoob.com/python3/python3-dictionary.html

要解析properties文件,在python中基本没有遇到这中情况,今天用python跑深度学习的时候,发现有些参数可以放在一个global.properties全局文件中,这样使用的时候更加方便。原理都是加载文件,然后用line方法进行解析判断”=”,自己从网上找到一个工具类,记录一下。

工具类 PropertiesUtiil.py
# -*- coding:utf-8 -*-
class Properties(object):

def __init__(self, fileName):
self.fileName = fileName
self.properties = {}

def __getDict(self,strName,dictName,value):

if(strName.find(‘.‘)>0):
k = strName.split(‘.‘)[0]
dictName.setdefault(k,{})
return self.__getDict(strName[len(k)+1:],dictName[k],value)
else:
dictName[strName] = value
return
def getProperties(self):
try:
pro_file = open(self.fileName, ‘Ur‘)
for line in pro_file.readlines():
line = line.strip().replace(‘\n‘, ‘‘)
if line.find("#")!=-1:
line=line[0:line.find(‘#‘)]
if line.find(‘=‘) > 0:
strs = line.split(‘=‘)
strs[1]= line[len(strs[0])+1:]
self.__getDict(strs[0].strip(),self.properties,strs[1].strip())
except Exception, e:
raise e
else:
pro_file.close()
return self.properties

通过上面的代码就可以解析了properties文件了。新建一个文件

global.properties 文件
a.name.last=jie
b.name.first=shi
#b.name=shijie
1
2
3
测试 test.py
from PropertiesUtil import Properties
dictProperties=Properties("global.properties").getProperties()
print dictProperties

控制台打印:

/usr/bin/python2.7 /home/tengxing/rude-carnie/test.py
{‘a‘: {‘name‘: {‘last‘: ‘jie‘}}, ‘b‘: {‘name‘: {‘first‘: ‘shi‘}}}

Process finished with exit code 0

我感觉还是挺方便的
————————————————
版权声明:本文为CSDN博主「牧羊人影视」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/tengxing007/java/article/details/72466187

https://www.runoob.com/python3/python3-dictionary.html

工作需要将Java项目的逻辑改为python执行,Java的很多配置文件都是.properties的,文件内容的格式是“键.键.键。。。=值”的格式例如A.B.C=value1,D.F=value2等。并且“#”用来注视。python没有专门处理properties格式的包,只有处理标准的ini格式的包。所以需要自己写一个python程序来处理。不说了上程序。

这里参考前面一篇://www.jb51.net/article/137390.htm

主要在前文的基础上,增加key.key.key=value的形式的支持

Util.py文件:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

class Properties(object):

  def __init__(self, fileName):

    self.fileName = fileName

    self.properties = {}

  def __getDict(self,strName,dictName,value):

    if(strName.find(‘.‘)>0):

      k = strName.split(‘.‘)[0]

      dictName.setdefault(k,{})

      return self.__getDict(strName[len(k)+1:],dictName[k],value)

    else:

      dictName[strName] = value

      return

  def getProperties(self):

    try:

      pro_file = open(self.fileName, ‘Ur‘)

      for line in pro_file.readlines():

        line = line.strip().replace(‘\n‘, ‘‘)

        if line.find("#")!=-1:

          line=line[0:line.find(‘#‘)]

        if line.find(‘=‘) > 0:

          strs = line.split(‘=‘)

          strs[1]= line[len(strs[0])+1:]

          self.__getDict(strs[0].strip(),self.properties,strs[1].strip())

    except Exception, e:

      raise e

    else:

      pro_file.close()

    return self.properties

filename.properties文件:


1

2

3

4

a.b.d=v1

a.c=v2

d.e=v3

f=v4

测试文件text.py:


1

2

3

from Util import Properties

dictProperties=Properties("filename.properties").getProperties()

print dictProperties

输出:

{‘a‘: {‘c‘: ‘v2‘, ‘b‘: {‘d‘: ‘v1‘}}, ‘d‘: {‘e‘: ‘v3‘}, ‘f‘: ‘v4‘}

更多关于Python

#! /usr/bin/env python

"""
A Python replacement for java.util.Properties class
This is modelled as closely as possible to the Java original.

Created - Anand B Pillai <[email protected]>
"""

import sys,os
import re
import time

class IllegalArgumentException(Exception):

def __init__(self, lineno, msg):
self.lineno = lineno
self.msg = msg

def __str__(self):
s=‘Exception at line number %d => %s‘ % (self.lineno, self.msg)
return s

class Properties(object):
""" A Python replacement for java.util.Properties """

def __init__(self, props=None):

# Note: We don‘t take a default properties object
# as argument yet

# Dictionary of properties.
self._props = {}
# Dictionary of properties with ‘pristine‘ keys
# This is used for dumping the properties to a file
# using the ‘store‘ method
self._origprops = {}

# Dictionary mapping keys from property
# dictionary to pristine dictionary
self._keymap = {}

self.othercharre = re.compile(r‘(?<!\\)(\s*\=)|(?<!\\)(\s*\:)‘)
self.othercharre2 = re.compile(r‘(\s*\=)|(\s*\:)‘)
self.bspacere = re.compile(r‘\\(?!\s$)‘)

def __str__(self):
s=‘{‘
for key,value in self._props.items():
s = ‘‘.join((s,key,‘=‘,value,‘, ‘))

s=‘‘.join((s[:-2],‘}‘))
return s

def __parse(self, lines):
""" Parse a list of lines and create
an internal property dictionary """

# Every line in the file must consist of either a comment
# or a key-value pair. A key-value pair is a line consisting
# of a key which is a combination of non-white space characters
# The separator character between key-value pairs is a ‘=‘,
# ‘:‘ or a whitespace character not including the newline.
# If the ‘=‘ or ‘:‘ characters are found, in the line, even
# keys containing whitespace chars are allowed.

# A line with only a key according to the rules above is also
# fine. In such case, the value is considered as the empty string.
# In order to include characters ‘=‘ or ‘:‘ in a key or value,
# they have to be properly escaped using the backslash character.

# Some examples of valid key-value pairs:
#
# key value
# key=value
# key:value
# key value1,value2,value3
# key value1,value2,value3 \
# value4, value5
# key
# This key= this value
# key = value1 value2 value3

# Any line that starts with a ‘#‘ is considerered a comment
# and skipped. Also any trailing or preceding whitespaces
# are removed from the key/value.

# This is a line parser. It parses the
# contents like by line.

lineno=0
i = iter(lines)

for line in i:
lineno += 1
line = line.strip()
# Skip null lines
if not line: continue
# Skip lines which are comments
if line[0] == ‘#‘: continue
# Some flags
escaped=False
# Position of first separation char
sepidx = -1
# A flag for performing wspace re check
flag = 0
# Check for valid space separation
# First obtain the max index to which we
# can search.
m = self.othercharre.search(line)
if m:
first, last = m.span()
start, end = 0, first
flag = 1
wspacere = re.compile(r‘(?<![\\\=\:])(\s)‘)
else:
if self.othercharre2.search(line):
# Check if either ‘=‘ or ‘:‘ is present
# in the line. If they are then it means
# they are preceded by a backslash.

# This means, we need to modify the
# wspacere a bit, not to look for
# : or = characters.
wspacere = re.compile(r‘(?<![\\])(\s)‘)
start, end = 0, len(line)

m2 = wspacere.search(line, start, end)
if m2:
# print ‘Space match=>‘,line
# Means we need to split by space.
first, last = m2.span()
sepidx = first
elif m:
# print ‘Other match=>‘,line
# No matching wspace char found, need
# to split by either ‘=‘ or ‘:‘
first, last = m.span()
sepidx = last - 1
# print line[sepidx]

# If the last character is a backslash
# it has to be preceded by a space in which
# case the next line is read as part of the
# same property
while line[-1] == ‘\\‘:
# Read next line
nextline = i.next()
nextline = nextline.strip()
lineno += 1
# This line will become part of the value
line = line[:-1] + nextline

# Now split to key,value according to separation char
if sepidx != -1:
key, value = line[:sepidx], line[sepidx+1:]
else:
key,value = line,‘‘

self.processPair(key, value)

def processPair(self, key, value):
""" Process a (key, value) pair """

oldkey = key
oldvalue = value

# Create key intelligently
keyparts = self.bspacere.split(key)
# print keyparts

strippable = False
lastpart = keyparts[-1]

if lastpart.find(‘\\ ‘) != -1:
keyparts[-1] = lastpart.replace(‘\\‘,‘‘)

# If no backspace is found at the end, but empty
# space is found, strip it
elif lastpart and lastpart[-1] == ‘ ‘:
strippable = True

key = ‘‘.join(keyparts)
if strippable:
key = key.strip()
oldkey = oldkey.strip()

oldvalue = self.unescape(oldvalue)
value = self.unescape(value)

self._props[key] = value.strip()

# Check if an entry exists in pristine keys
if self._keymap.has_key(key):
oldkey = self._keymap.get(key)
self._origprops[oldkey] = oldvalue.strip()
else:
self._origprops[oldkey] = oldvalue.strip()
# Store entry in keymap
self._keymap[key] = oldkey

def escape(self, value):

# Java escapes the ‘=‘ and ‘:‘ in the value
# string with backslashes in the store method.
# So let us do the same.
newvalue = value.replace(‘:‘,‘\:‘)
newvalue = newvalue.replace(‘=‘,‘\=‘)

return newvalue

def unescape(self, value):

# Reverse of escape
newvalue = value.replace(‘\:‘,‘:‘)
newvalue = newvalue.replace(‘\=‘,‘=‘)

return newvalue

def load(self, stream):
""" Load properties from an open file stream """

# For the time being only accept file input streams
if type(stream) is not file:
raise TypeError,‘Argument should be a file object!‘
# Check for the opened mode
if stream.mode != ‘r‘:
raise ValueError,‘Stream should be opened in read-only mode!‘

try:
lines = stream.readlines()
self.__parse(lines)
except IOError, e:
raise

def getProperty(self, key):
""" Return a property for the given key """

return self._props.get(key,‘‘)

def setProperty(self, key, value):
""" Set the property for the given key """

if type(key) is str and type(value) is str:
self.processPair(key, value)
else:
raise TypeError,‘both key and value should be strings!‘

def propertyNames(self):
""" Return an iterator over all the keys of the property
dictionary, i.e the names of the properties """

return self._props.keys()

def list(self, out=sys.stdout):
""" Prints a listing of the properties to the
stream ‘out‘ which defaults to the standard output """

out.write(‘-- listing properties --\n‘)
for key,value in self._props.items():
out.write(‘‘.join((key,‘=‘,value,‘\n‘)))

def store(self, out, header=""):
""" Write the properties list to the stream ‘out‘ along
with the optional ‘header‘ """

if out.mode[0] != ‘w‘:
raise ValueError,‘Steam should be opened in write mode!‘

try:
out.write(‘‘.join((‘#‘,header,‘\n‘)))
# Write timestamp
tstamp = time.strftime(‘%a %b %d %H:%M:%S %Z %Y‘, time.localtime())
out.write(‘‘.join((‘#‘,tstamp,‘\n‘)))
# Write properties from the pristine dictionary
for prop, val in self._origprops.items():
out.write(‘‘.join((prop,‘=‘,self.escape(val),‘\n‘)))

out.close()
except IOError, e:
raise

def getPropertyDict(self):
return self._props

def __getitem__(self, name):
""" To support direct dictionary like access """

return self.getProperty(name)

def __setitem__(self, name, value):
""" To support direct dictionary like access """

self.setProperty(name, value)

def __getattr__(self, name):
""" For attributes not found in self, redirect
to the properties dictionary """

try:
return self.__dict__[name]
except KeyError:
if hasattr(self._props,name):
return getattr(self._props, name)

if __name__=="__main__":
p = Properties()
p.load(open(‘test2.properties‘))
p.list()
print p
print p.items()
print p[‘name3‘]
p[‘name3‘] = ‘changed = value‘
print p[‘name3‘]
p[‘new key‘] = ‘new value‘
p.store(open(‘test2.properties‘,‘w‘))

参考来源:http://blog.csdn.net/bobzhangshaobo/article/details/47617107 我们都是在java里面遇到要解析properties文件,在python中基本没有遇到这中情况,今天用python跑深度学习的时候,发现有些参数可以放在一个global.properties全局文件中,这样使用的时候更加方便。原理都是加载文件,然后用line方法进行解析判断”=”,自己从网上找到一个工具类,记录一下。

工具类 PropertiesUtiil.py

# -*- coding:utf-8 -*-
class Properties(object):  

    def __init__(self, fileName):
        self.fileName = fileName
        self.properties = {}  

    def __getDict(self,strName,dictName,value):  

        if(strName.find(‘.‘)>0):
            k = strName.split(‘.‘)[0]
            dictName.setdefault(k,{})
            return self.__getDict(strName[len(k)+1:],dictName[k],value)
        else:
            dictName[strName] = value
            return
    def getProperties(self):
        try:
            pro_file = open(self.fileName, ‘Ur‘)
            for line in pro_file.readlines():
                line = line.strip().replace(‘\n‘, ‘‘)
                if line.find("#")!=-1:
                    line=line[0:line.find(‘#‘)]
                if line.find(‘=‘) > 0:
                    strs = line.split(‘=‘)
                    strs[1]= line[len(strs[0])+1:]
                    self.__getDict(strs[0].strip(),self.properties,strs[1].strip())
        except Exception, e:
            raise e
        else:
            pro_file.close()
        return self.properties  

通过上面的代码就可以解析了properties文件了。新建一个文件

global.properties 文件

a.name.last=jie
b.name.first=shi
#b.name=shijie

测试 test.py

from PropertiesUtil import Properties
dictProperties=Properties("global.properties").getProperties()
print dictProperties

控制台打印:

/usr/bin/python2.7 /home/tengxing/rude-carnie/test.py
{‘a‘: {‘name‘: {‘last‘: ‘jie‘}}, ‘b‘: {‘name‘: {‘first‘: ‘shi‘}}}

Process finished with exit code 0

我感觉还是挺方便的,就对做深度学习来说吧,把模型的的位置,训练数据放在一个global.properties文件中,方便管理。

# -*- coding:utf-8 -*-class Properties(object):

    def __init__(self, fileName):        self.fileName = fileName        self.properties = {}

    def __getDict(self,strName,dictName,value):

        if(strName.find(‘.‘)>0):            k = strName.split(‘.‘)[0]            dictName.setdefault(k,{})            return self.__getDict(strName[len(k)+1:],dictName[k],value)        else:            dictName[strName] = value            return    def getProperties(self):        try:            pro_file = open(self.fileName, ‘r‘)            for line in pro_file.readlines():                line = line.strip().replace(‘\n‘, ‘‘)                if line.find("#")!=-1:                    line=line[0:line.find(‘#‘)]                if line.find(‘=‘) > 0:                    strs = line.split(‘=‘)                    strs[1]= line[len(strs[0])+1:]                    self.__getDict(strs[0].strip(),self.properties,strs[1].strip())        except:            raise        else:            pro_file.close()        return self.properties

## from PropertiesUtil import Properties# dictProperties=Properties("global.properties").getProperties()# print dictProperties#

file_path = r‘D:\backup\PycharmProjects\charm123\prop.properties‘dictProperties=Properties(file_path).getProperties()print (dictProperties)print (type(dictProperties))print (len(dictProperties))print (dictProperties[‘url‘])print (dictProperties[‘driver‘])hang1=1try:    hang1=dictProperties[‘hang1‘]except :    hang1=0

print (hang1)

dict = {‘Name‘: ‘Runoob‘, ‘Age‘: 7, ‘Class‘: ‘First‘}

dict[‘Age‘] = 88  # 更新 Agedict[‘School‘] = "添加信息"  # 添加信息

print("dict[‘Age‘]: ", dict[‘Age‘])print("dict[‘School‘]: ", dict[‘School‘])

del dict[‘Name‘]  # 删除键 ‘Name‘dict.clear()  # 清空字典del dict  # 删除字典

print("dict[‘Age‘]: ", dict[‘Age‘])print("dict[‘School‘]: ", dict[‘School‘])

原文地址:https://www.cnblogs.com/xinxihua/p/12636650.html

时间: 2024-10-08 17:26:53

xls5-解析properties文件,在python中基本没有遇到的相关文章

java解析properties文件

在自动化测试过程中,经常会有一些公用的属性要配置,以便后面给脚本使用,我们可以选择xml, excel或者json格式来存贮这些数据,但其实java本身就提供了properties类来处理properties文件,虽然名字叫properties,其实打开它发现就是一个记事本的文件,所以看起来也比较直观,下面是解析properties文件的实现代码. properties文件里存贮的样子是这样的,然后给他保存为xxx.properties即可. gsBAMUserName1=automation_

解析prototxt文件的python库 prototxt-parser(使用parsy自定义文件格式解析)

解析prototxt文件的python库 prototxt-parser https://github.com/yogin16/prototxt_parser https://test.pypi.org/project/prototxt-parser1.yield让函数执行支持分段,让函数支持了记忆和状态,能够让一个函数变成状态机,这样一个状态机的执行流程可能直接表达在一个函数中,让整个处理流程更加顺畅.2.parsy的optional,Returns a parser that expects

java加载properties文件的六中基本方式实现

java加载properties文件的方式主要分为两大类:一种是通过import java.util.Properties类中的load(InputStream in)方法加载: 另一种是通过import java.util.ResourceBundle类的getBundle(String baseName)方法加载. 注意:一定要区分路径格式 实现代码如下: 1 package com.util; 2 3 import java.io.FileInputStream; 4 import jav

CSV文件在Python中的几种处理方式

Comma Separated Values,简称CSV,它是一种以逗号分隔数值的文件类型.在数据库或电子表格中,它是最常见的导入导出格式,它以一种简单而明了的方式存储和共享数据,CSV文件通常以纯文本的方式存储数据表.今天,我将给大家分享在Python中如何操作CSV文件. 一.数据源 首先,我们来看看本次操作的数据源,图1 CSV文件是在Excel中打开的,图2 CSV文件是在Notepad++中打开的,我们在图2中可以看到数值之间是以逗号分隔开的,每行末尾是CR回车符和LF换行符(请注意,

解析Properties文件

/** * 传入需要解析的文件属性,传入文件的路径 * @param para 需要获取的属性名称.也就是键值对中的键名称 * @param filepath * @return */ public static String getPara(String para,String filepath){ InputStream is = null; try{ Properties properties = new Properties(); //接下来需要获取.properties的文件路径: S

实现自动解析properties文件并装配到Bean

主要实现了,配置的属性就装配, 没有配置的属性不装配 思路: 1 . 通过反射获取类内部所有方法名称 2 . 获取perperties 的key集合 3 .  处理字符串,比较两个匹配,如果匹配成功就使用Method.invoke()方法 , 执行匹配成功的方法 JAVA代码 1 package bingosoft.metro.xmgl.cx.redisUtil; 2 3 import java.io.IOException; 4 import java.lang.reflect.Field;

读取并解析properties文件

public class SysConfig { private static final Properties properties = new Properties(); static{ Resource rs1 = new ClassPathResource("sys-config.properties"); try { properties.load(rs1.getInputStream()); } catch (Exception e) { e.printStackTrace

maven 项目打包时无法解析读取properties文件

在做项目时遇见一个问题,无法解析properties文件的 内容 异常为 Could not resolve placeholder ......... 在此之前均有做相关的 配置 但是从未出现过如上异常,困惑了很久,最后把 war包提取出来得知   properties文件未被加载进项目中,因此无法识别. 但这的原因是为什么呢   ,原来此项目采用的是maven配置,但是maven在打包时将丢失properties文件,原因maven执行compile是只会扫描*.class文件. 那么这种请

Python解析excel文件并存入sqlite数据库

功能:1.数据库设计 建立数据库2.Python解析excel文件3.Python读取文件名并解析4.将解析的数据存储入库 一 建立数据库 根据需求建立数据库,建立了两个表,并保证了可以将数据存储到已有的数据库中,代码如下: import sqlite3 def createDataBase(): cn = sqlite3.connect('check.db') cn.execute('''CREATE TABLE IF NOT EXISTS TB_CHECK (ID integer PRIMA