python常用方法

来源:互联网 发布:户外广告液晶屏软件 编辑:程序博客网 时间:2024/06/06 06:43

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

进制转换

hex(255) #整数转换为16进制数int('13',base=6) #base=6标识前面的数是一个6进制数,所以结果是9oct(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/0ZeroDivisionError: 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 loggingimport oslogging.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,exceptionTraceback (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')有的时候我们需要根据类中方法的字符串名称去调用这个方法,可以使用getattrfunc_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或listIn [2]: import jsonIn [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 A1 B2 C

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

>>> for x, y in [(1, 1), (2, 4), (3, 9)]:...     print(x, y)...1 12 43 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 reducedef 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 == 1list(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 EnumMonth = 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@uniqueclass 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]: userOut[29]: [User(id=1, name='Joy'), User(id=2, name='Tom')]In [30]: for id, name in user:    ...:     print(id, name)    ...:     1 Joy2 TomIn [36]: user[0].nameOut[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 jsondef 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 = scores = 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.555In [34]: round(a, 2)Out[34]: 1.55In [35]: b = Decimal(str(a))In [37]: c = round(b, 2)In [38]: cOut[38]: Decimal('1.56')In [39]: float(c)Out[39]: 1.56
0 0
原创粉丝点击