当前位置:   article > 正文

python编程小技巧_python 编程小技巧

python 编程小技巧

一. 获取当前模块的类名

#coding:utf-8
import sys

class People():
    def __init__(self, name):
        print "name:", name
        print "*"*30
        print "class_name:", self.__class__.__name__

if __name__ == "__main__":
    p = People("zhangsan")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

运行结果

name: zhangsan
******************************
class_name: People
  • 1
  • 2
  • 3

二. 监控函数的运行

#coding:utf-8
import sys

def fun_1(name, age):
    print "name: %s, age: %s" %(name, age)

def fun_2(school):
    print "school: %s" %(school)

def run_fun(fun_name, *arg):
    try:
        fun_name(*arg)
    except Exception,e:
        print "error\t error_type=%s\t error_info=%s" %(fun_name.__name__, repr(e))

if __name__ == "__main__":
    run_fun(fun_1, "zhangsan", 29)
    run_fun(fun_2, "Henan Politecnic University")
    run_fun(fun_2, "Henan Politecnic University", "test")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

运行结果

name: zhangsan, age: 29
school: Henan Politecnic University
error	 error_type=fun_2	 error_info=TypeError('fun_2() takes exactly 1 argument (2 given)',)
  • 1
  • 2
  • 3

三. split分割字符串

str.split(str="", num=string.count(str))
  • 1

参数:

  • str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
  • num – 分割次数。默认为 -1, 即分隔所有。

返回值:返回分割后的字符串列表。

示例:

print "hehe nlj 20".split(" ")
print "hehe nlj 20".split(" ", 1)
  • 1
  • 2

运行结果

['hehe', 'nlj', '20']
['hehe', 'nlj 20']
  • 1
  • 2

四. 写文件的两种方法

示例

#coding:utf-8
import sys

f = open("write.txt", "w")
my_str = "hello world !!!"
#方法1:
f.write(my_str+"\n")
#方法2:
print >> f, my_str
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

运行结果:

以上两种方法的效果一样

hello world !!!
hello world !!!
  • 1
  • 2

五. 加载不同类型的配置文件

示例

目录结构如下:

|—load_conf.py

| ----conf

​ |----test_1.json

​ |----test_2.json

​ |----test_3.cfg

test_1.json

[
"Demo1Feature",
"Demo2Feature",
"Demo3Feature"
]
  • 1
  • 2
  • 3
  • 4
  • 5

test_2.json

{
  "ug_model":
  {
    "name":"ug_model",
    "feature_name":[1021001003, 1021401001, 1021001004, 1021401002]
  },
  "outlier_model":
  {
    "name":"outlier_model",
    "feature_name":[1031001003, 1031401001, 1031001004, 1031401002]
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

test_3.cfg

[default]
name="zhangsan"
age="30"
school="Henan Politecnic University"
  • 1
  • 2
  • 3
  • 4

load_conf.py代码

#coding:utf-8
import json
import glob
import re
import sys
import ConfigParser

def load_json():
    featurelib_conf_dir = "conf"
    featurelib_conf_suffix_extension = ".json"
    for feature_lib_conf_file in glob.glob(featurelib_conf_dir+'/*'+ featurelib_conf_suffix_extension):
        with open(feature_lib_conf_file, 'r') as f:
            feature_production_conf = json.loads(re.sub('(\/\/.*)', '', re.sub('(/\*(.*?)\*/)', '', f.read(), flags=re.S)))
            print feature_lib_conf_file, "*"*30, type(feature_production_conf)
            if isinstance(feature_production_conf, list):
                for k in feature_production_conf:
                    print k
            elif isinstance(feature_production_conf, dict):
                for k,v in feature_production_conf.items():
                    print k,v
def load_cfg():
    conf_dir = "conf"
    conf_suffix_extension = ".cfg"
    for conf_file in glob.glob(conf_dir+'/*'+conf_suffix_extension):
        print "conf_file:", conf_file, "*"*30
        cfg = ConfigParser.ConfigParser()
        cfg.read(conf_file)
        sections = cfg.sections()
        for section in sections:
            print "section:", section, "+"*20
            for k,v in cfg.items(section):
              print k,"-->", v

if __name__ == "__main__":
    load_json()
    load_cfg()
  • 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
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

运行结果:

conf/test_1.json ****************************** <type 'list'>
Demo1Feature
Demo2Feature
Demo3Feature
conf/test_2.json ****************************** <type 'dict'>
outlier_model {u'feature_name': [1031001003, 1031401001, 1031001004, 1031401002], u'name': u'outlier_model'}
ug_model {u'feature_name': [1021001003, 1021401001, 1021001004, 1021401002], u'name': u'ug_model'}
conf_file: conf/test_3.cfg ******************************
section: default ++++++++++++++++++++
name --> "zhangsan"
age --> "30"
school --> "Henan Politecnic University"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/44645?site
推荐阅读
相关标签
  

闽ICP备14008679号