python英译汉库模块_翻译|Python标准功能库1

上班的时候偷懒,把Python帮助里的标准功能库1过了一遍,顺便翻译了一下,虽然我知道基本没有人看,但不是说21世纪编程能力是基本的生存力嘛。

通过阅读本文,你将了解Python的11个标准功能库1.操作系统接口库

2.文件通配符

3.命令行参数

4.错误输入重定向及终止程序

5.字符匹配

6.数学库

7.互联网访问

8.日期与时间

9.数据压缩

10.性能评价

11.质量控制

1.操作系统接口库

OS操作系统模块提供了一系列的与操作系统的交互。要尽可能确保使用Import os方式而不是from os import *. 这将使得保持os.open()映射自不同操作的内建的open()函数。内建的dir()和help()函数是在os大模块中非常有用的辅助手段。>>>import os

>>>os.getcwd()  #返回当前工作路径

>>>os.chdir('/abc/abc') #改变当前的工作路径

>>>os.system('mkdir today') #在系统命令行运行mkdir

>>>dir(os) #返回所有的功能模块列表

>>>help(os) #返回创建自模块文档的手册

对于日常的文件与目录管理,更容易使用的shutil模块能够提供更高层次的接口。>>>import shutil

>>>shutil.copyfile(src,

dst, *, follow_symlinks=True)  #复制文件

>>>shutil.move(src, dst,

copy_function=copy2) #移动文件或目录

2.文件通配符

glob模块提供了一个通过使用通配符搜索目录并生成文件清单的功能>>>import glob

>>>glob.glob('*.py') #返回后缀是py的所有文件列表

3.命令行参数

一般的脚本工具都需要处理命令行参数。这些参数都以列表的形式存放在sys模块的argv属性中。下面的例子是在命令行运行python demo.py one two three的输出结果:>>>import sys

>>>print(sys.argv)

['demo.py','one','two','three']

getopt模块会根据协议,通过使用Unix的getopt()函数来处理sys.argv。argparse提供了更强大和更有弹性的处理命令行程序。

4.错误输入重定向及终止程序

sys模块还具有stdin,stdout和stderr属性,其中stderr主要用于弹出警告与错误信息,并使它们可视化,就算当stdout已经被重定向了。>>>sys.stderr.write('Warning message')

最常用的结束脚本运行的命令是sys.exit()

5.字符匹配

re模块提供了常用的高级字符处理工具。对于复杂的匹配与处理,常规表达式提供了简明的方案:>>> import re

>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')

['foot', 'fell', 'fastest']

>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')

'cat in the hat'

当如果只需要简单功能时,可以直接使用字符串,因为这样易读和易于调试。>>> 'tea for too'.replace('too', 'two')

'tea for two'

6.数学库

math模块提供了处理浮点运算时访问C语言库的能力>>> import math

>>> math.cos(math.pi / 4)

0.70710678118654757

>>> math.log(1024, 2)

10.0

random模块提供了随机选择工具>>> import random

>>> random.choice(['apple', 'pear', 'banana']) #随机选择列表项

'apple'

>>> random.sample(range(100), 10)   # 100以内的10个随机数样本

[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]

>>> random.random()    # 随机浮点数

0.17970987693706186

>>> random.randrange(6)    # 6以内的随机整数

4

statistics模块提供了基础的数值统计功能(平均数、中间数、偏差等)>>> import statistics

>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]

>>> statistics.mean(data)

1.6071428571428572

>>> statistics.median(data)

1.25

>>> statistics.variance(data)

1.3720238095238095

在SciPy项目中有许多做其它数值运算的模块。

7.互联网访问

有许多模块能够提供了访问互联网和处理网络协议,有两个最简单的,urllib.request是从URLs来接收数据,smtplib用于发送邮件(需要邮件服务器的支持)>>> from urllib.request import urlopen

>>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:

...     for line in response:

...         line = line.decode('utf-8')  # Decoding the binary data to text.

...         if 'EST' in line or 'EDT' in line:  # look for Eastern Time

...             print(line)


Nov. 25, 09:43:32 PM EST

>>> import smtplib

>>> server = smtplib.SMTP('localhost')

>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',

... """To: jcaesar@example.org

... From: soothsayer@example.org

...

... Beware the Ides of March.

... """)

>>> server.quit()

8.日期与时间

datetime模块提供了多种处理日期与时间的类,支持日期与时间的数值运算,主要加强了数值运算效率与输出格式的处理。这个模块也支持时区对象。>>> # 简单的日期建立与格式化

>>> from datetime import date

>>> now = date.today()

>>> now

datetime.date(2003, 12, 2)

>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")

'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> # 支持日历运算的日期

>>> birthday = date(1964, 7, 31)

>>> age = now - birthday

>>> age.days

14368

9.数据压缩

常见的数据归档与压缩支持模块:zlib,gzip,bz2,lzma,zipfile,tarfile>>> import zlib

>>> s = b'witch which has which witches wrist watch'

>>> len(s)

41

>>> t = zlib.compress(s)

>>> len(t)

37

>>> zlib.decompress(t)

b'witch which has which witches wrist watch'

>>> zlib.crc32(s) #检验和

226805979

10.性能评价

有些Python开发者在开发过程中,想知道不同的方法导致的性能上的差异有多大,系统提供了测量工具来即时回答这个问题。举个例子,使用数组的打包与解包特性来替代传统的清理参数的方法具有很强的吸引力,timeit模块可以快速展示性能的优势:>>> from timeit import Timer

>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()

0.57535828626024577

>>> Timer('a,b = b,a', 'a=1; b=2').timeit()

0.54962537085770791

相比于timeit的精细层面,profile和pstats模块提供了工具来识别大块代码的时间消耗。

11.质量控制

一个开发高质量软件的方法是对每个功能写出测试案例,并在开发时经常运行测试。doctest模块提供一个嵌入式工具来扫描和校验测试。测试的构建和剪切粘贴一样的简单。通过提供用户一个例子和它允许doctest模块来确认代码对于文档来讲仍然为真,来优化文档。def average(values):

"""Computes the arithmetic mean of a list of numbers.

>>> print(average([20, 30, 70]))

40.0

"""

return sum(values) / len(values)

import doctest

doctest.testmod()   # 自动检验嵌入式测试

unittest不是象doctest一样毫不费力的,它允许更多的强化整体测试,通过把测试维护在单独的文件里。import unittest

class TestStatisticalFunctions(unittest.TestCase):

def test_average(self):

self.assertEqual(average([20, 30, 70]), 40.0)

self.assertEqual(round(average([1, 5, 7]), 1), 4.3)

with self.assertRaises(ZeroDivisionError):

average([])

with self.assertRaises(TypeError):

average(20, 30, 70)

unittest.main()  # Calling from the command line invokes all tests

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值