python常用方法

参考链接:http://www.liaoxuefeng.com/

进制转换

hex(255) #整数转换为16进制数
int('13',base=6) #base=6标识前面的数是一个6进制数,所以结果是9
oct(9) #整数转换为8进制数
bin(9) #整数转换为2进制数
int(011) #八进制数转换为十进制数

检测字符编码

>>> import chardet
>>> chardet.detect(code)

打开文件

f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore')

遍历目录下文件名

for root,dirs,files in os.walk(r'./XMLMessage'):
    for fn in files:
        print fn

单元测试

使用python -m doctest aa.py 可以运行单元测试
def scale(w, h):
'''
    >>> scale(100, 100)
    (None, None)
    >>> scale(710, 100)
    (618, 87)
    '''
if w > 618 or h > 618:
return get_dest_wh_scale(w, h, 618)
elif w > 480 or h > 480:
return get_dest_wh_scale(w, h, 480)
elif w > 320 or h > 320:
return get_dest_wh_scale(w, h, 320)
elif w > 240 or h > 240:
return get_dest_wh_scale(w, h, 240)
else:
return None, None

traceback 错误追踪

import traceback  
try:  
    1/0  
except Exception,e:  
    traceback.print_exc() 

Traceback (most recent call last):
File "test_traceback.py", line 3, in <module>
1/0
ZeroDivisionError: integer division or modulo by zero

如果想将结果保存在某个变量,可以使用format_exc()

import traceback  
try:  
    1/0  
except Exception,e:  
    traceback.format_exc()

调用linux命令的时候,不要使用os.system(),使用subprocess

cmds = ['convert', gif_fp, '-coalesce', 'temporary.gif']
subprocess.check_output(cmds, shell=False)

日志

import logging
import os
logging.basicConfig(format="%(levelname)s,%(message)s",filename=os.path.join(os.getcwd(),'log.txt'),level=logging.DEBUG)
log = logging.getLogger('root')   #Logger对象try:
    raise Exception,u'错误异常'except:
    log.exception('exception')  #异常信息被自动添加到日志消息中  
打开文件,显示如下:
'''ERROR,exception
Traceback (most recent call last):
  File "E:\project\py\src\log3.py", line 12, in <module>
    raise Exception,u'错误异常'
Exception: 错误异常
'''
http://www.cnblogs.com/BeginMan/p/3328671.html

pip

通过pip freeze > requirements.txt导出项目所需要的包。
通过pip install -r requirements.txt安装文件中所有的包。

命名空间

locals() 返回本地命名空间
globals() 返回全局命名空间

从类中取出方法

class TestClass(object):
    @classmethod
    def test_func(self):
        print('test_func')

有的时候我们需要根据类中方法的字符串名称去调用这个方法,可以使用getattr

func_get = getattr(TestClass, 'test_func')
func_get()   # 就可以执行啦

字典翻转

In [72]: ori_dict = {'a':'b', 'c':'d'}

In [73]: dict((v, i) for i, v in ori_dict.items())
Out[73]: {'b': 'a', 'd': 'c'}

格式化输出

格式化输出dict或list
In [2]: import json
In [3]: a = {'a':{'b':1}}

In [4]: json.dumps(a, indent=1)
Out[4]: '{\n "a": {\n  "b": 1\n }\n}'

In [5]: print(json.dumps(a, indent=1, ensure_ascii=False))
{
 "a": {
  "b": 1
 }
}

对list迭代时同时获取下标和值

for i, value in enumerate(['A', 'B', 'C']):
    print(i, value)

0 A
1 B
2 C

对list中的元素是相同长度的可切片的元素时,可以用如下语法获取里层的值

>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
...     print(x, y)
...
1 1
2 4
3 9

列表解析

>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']

map/reduce

map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回

>>> def f(x):
...     return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]

reduce把一个函数作用在一个序列[x1, x2, x3, …]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算

>>> from functools import reduce
>>> def add(x, y):
...     return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25

综合应用:字符串转化为整数

from functools import reduce

def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

def str2int(s):
    return reduce(lambda x, y: x * 10 + y, map(char2num, s))

filter

Python内建的filter()函数用于过滤序列。
和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
可见用filter()这个高阶函数,关键在于正确实现一个“筛选”函数
例如,在一个list中,删掉偶数,只保留奇数,可以这么写:

def is_odd(n):
    return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))

sorted

排序也是在程序中经常用到的算法。无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小。如果是数字,我们可以直接比较,但如果是字符串或者两个dict呢?直接比较数学上的大小是没有意义的,因此,比较的过程必须通过函数抽象出来

>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]

默认情况下,对字符串排序,是按照ASCII的大小比较的,由于’Z’ < ‘a’,结果,大写字母Z会排在小写字母a的前面
现在,我们提出排序应该忽略大小写,按照字母序排序。要实现这个算法。我们给sorted传入key函数,即可实现忽略大小写的排序

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']

要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']

枚举类

from enum import Enum

Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
Month.Jan.name  # 获取枚举常量的名称
Month.Jan.value  # 获取枚举常量的值, value属性则是自动赋给成员的int常量,默认从1开始计数

for name, member in Month.__members__.items():  # 枚举它的所有成员
    print(name, '=>', member, ',', member.value)

如果需要更精确地控制枚举类型,可以从Enum派生出自定义类
@unique装饰器可以帮助我们检查保证没有重复值

from enum import Enum, unique

@unique
class Weekday(Enum):
    Sun = 0 # Sun的value被设定为0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6

os模块–系统环境和文件

  1. 在操作系统中定义的环境变量,全部保存在os.environ这个变量中,要获取某个环境变量的值,可以调用os.environ.get(‘key’)

  2. 操作文件和目录
    操作文件和目录的函数一部分放在os模块中,一部分放在os.path模块中


# 查看当前目录的绝对路径:
>>> os.path.abspath('.')
'/Users/michael'
# 在某个目录下创建一个新目录,首先把新目录的完整路径表示出来:
>>> os.path.join('/Users/michael', 'testdir')
'/Users/michael/testdir'
# 然后创建一个目录:
>>> os.mkdir('/Users/michael/testdir')
# 删掉一个目录:
>>> os.rmdir('/Users/michael/testdir')

# 把两个路径合成一个时,不要直接拼字符串,而要通过os.path.join()函数,这样可以正确处理不同操作系统的路径分隔符
os.path.join(path1, path2)

# 要拆分路径时,也不要直接去拆字符串,而要通过os.path.split()函数,这样可以把一个路径拆分为两部分,后一部分总是最后级别的目录或文件名
>>> os.path.split('/Users/michael/testdir/file.txt')
('/Users/michael/testdir', 'file.txt')

# os.path.splitext()可以直接让你得到文件扩展名
>>> os.path.splitext('/path/to/file.txt')
('/path/to/file', '.txt')

# 对文件重命名:
>>> os.rename('test.txt', 'test.py')
# 删掉文件:
>>> os.remove('test.py')

# 列出当前目录下的所有目录
>>> [x for x in os.listdir('.') if os.path.isdir(x)]
['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Applications', 'Desktop', ...]

# 列出所有的.py文件
>>> [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
['apis.py', 'config.py', 'models.py', 'pymonitor.py', 'test_db.py', 'urls.py', 'wsgiapp.py']

但是复制文件的函数居然在os模块中不存在!原因是复制文件并非由操作系统提供的系统调用
幸运的是shutil模块提供了copyfile()的函数,你还可以在shutil模块中找到很多实用函数,它们可以看做是os模块的补充


namedtuple

namedtuple 用以构建只有少数属性但是没有方法的对象,比如数据库条目

In [23]: User = collections.namedtuple('User', ['id', 'name'])

In [28]: user = [User(1, 'Joy'), User(2, 'Tom')]

In [29]: user
Out[29]: [User(id=1, name='Joy'), User(id=2, name='Tom')]

In [30]: for id, name in user:
    ...:     print(id, name)
    ...:     
1 Joy
2 Tom

In [36]: user[0].name
Out[36]: 'Joy'

json

把Python对象变成一个JSON,dumps()方法返回一个str,内容就是标准的JSON。类似的,dump()方法可以直接把JSON写入一个file-like Object

>>> import json
>>> d = dict(name='Bob', age=20, score=88)
>>> json.dumps(d)
'{"age": 20, "score": 88, "name": "Bob"}'

要把JSON反序列化为Python对象,用loads()或者对应的load()方法,前者把JSON的字符串反序列化,后者从file-like Object中读取字符串并反序列化
由于JSON标准规定JSON编码是UTF-8,所以我们总是能正确地在Python的str与JSON的字符串之间转换

>>> json_str = '{"age": 20, "score": 88, "name": "Bob"}'
>>> json.loads(json_str)
{'age': 20, 'score': 88, 'name': 'Bob'}

将自定义类序列化为json对象

import json

def student2dict(std):
    return {
        'name': std.name,
        'age': std.age,
        'score': std.score
    }

def dict2student(d):
    return Student(d['name'], d['age'], d['score'])

class Student(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

s = Student('Bob', 20, 88)

>>> print(json.dumps(s, default=student2dict))  # 可选参数default就是把任意一个对象变成一个可序列为JSON的对象
{"age": 20, "name": "Bob", "score": 88}

>>> json_str = '{"age": 20, "score": 88, "name": "Bob"}'
>>> print(json.loads(json_str, object_hook=dict2student))  # object_hook函数负责把dict转换为Student实例
<__main__.Student object at 0x10cd3c190>

round, 浮点数

因为浮点数精度问题, round可能结果并不和预期一致, 这时候可以使用decimal

In [33]: a = 1.555

In [34]: round(a, 2)
Out[34]: 1.55

In [35]: b = Decimal(str(a))
In [37]: c = round(b, 2)

In [38]: c
Out[38]: Decimal('1.56')

In [39]: float(c)
Out[39]: 1.56

单元测试

使用python -m doctest aa.py 可以运行单元测试


def scale(w, h):
'''
    >>> scale(100, 100)
    (None, None)
    >>> scale(710, 100)
    (618, 87)
    '''
if w > 618 or h > 618:
return get_dest_wh_scale(w, h, 618)
elif w > 480 or h > 480:
return get_dest_wh_scale(w, h, 480)
elif w > 320 or h > 320:
return get_dest_wh_scale(w, h, 320)
elif w > 240 or h > 240:
return get_dest_wh_scale(w, h, 240)
else:
return None, None

命令行命令调用

subprocess

command = "ls -a"
status = subprocess.call(command, shell=True)
if status != 0:
    print("faild")

log

import logging
import os
logging.basicConfig(format="%(levelname)s,%(message)s",filename=os.path.join(os.getcwd(),'log.txt'),level=logging.DEBUG)
log = logging.getLogger('root')   #Logger对象try:
    raise Exception,u'错误异常'except:
    log.exception('exception')  #异常信息被自动添加到日志消息中  
打开文件,显示如下:
'''ERROR,exception
Traceback (most recent call last):
  File "E:\project\py\src\log3.py", line 12, in <module>
    raise Exception,u'错误异常'
Exception: 错误异常
'''
http://www.cnblogs.com/BeginMan/p/3328671.html

python类动态增加(替换)方法

types

import types

class Ab:
    def aa(self):
        return 'aa'

def aa(self):
    return 'aa_new'

ab = Ab()
ab.aa = types.MethodType(aa, ab)

ab.aa()  # 输出 aa_new

普通dict生成OrderedDict

collections.OrderedDict(sorted(d.items(),key = lambda t:t[0]))

格式化打印python对象

import datetime
import json
import re


def print_format_result(result):
    class DatetimeEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, datetime.datetime):
                return "datetime.datetime({0}, {1}, {2})".format(obj.year, obj.month, obj.day)
            else:
                return json.JSONEncoder.default(self, obj)

    def obj_contain_datetime_convert_to_str(obj):
        if isinstance(obj, (list, tuple)):
            new_obj = []
            for value in obj:
                new_obj.append(obj_contain_datetime_convert_to_str(value))
        elif isinstance(obj, dict):
            new_obj = {}
            for key, value in obj.items():
                new_obj[obj_contain_datetime_convert_to_str(key)] = obj_contain_datetime_convert_to_str(value)
        elif isinstance(obj, datetime.datetime):
            new_obj = "datetime.datetime({0}, {1}, {2})".format(obj.year, obj.month, obj.day)
        elif isinstance(obj, (str, int, float)):
            new_obj = obj
        elif isinstance(obj, type(None)):
            new_obj = obj
        else:
            raise TypeError("do not support data type, type(obj)={0}".format(type(obj)))

        return new_obj

    result = obj_contain_datetime_convert_to_str(result)
    result = json.dumps(result, indent=4, ensure_ascii=False, cls=DatetimeEncoder)
    result = re.sub(r'"(datetime.datetime\(.*?\))"', r'\1', result)
    print(result)


if __name__ == "__main__":
    a = {datetime.datetime(2016, 1, 1): datetime.datetime(2016, 1, 1)}
    print_format_result(a)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值