python基础语法12-标准库

Python 标准库非常庞大,所提供的组件涉及范围十分广泛,这个库包含了多个内置模块 (以 C 编写),Python 程序员必须依靠它们来实现系统级功能,例如文件 I/O,此外还有大量以 Python 编写的模块,提供了日常编程中许多问题的标准解决方案。其中有些模块经过专门设计,通过将特定平台功能抽象化为平台中立的 API 来鼓励和加强 Python 程序的可移植性。
Windows 版本的 Python 安装程序通常包含整个标准库,往往还包含许多额外组件。
对于类 Unix 操作系统,Python 通常会分成一系列的软件包,因此可能需要使用操作系统所提供的包管理工具来获取部分或全部可选组件。
一、内置函数:
python解释器内置了很多函数和类型,任何时候都可以使用。如:
abs(),aiter(),all(),any(),anext(),ascii(),bin(),bool(),breakpoint(),bytearray()
bytes(),callable(),chr(),classmethod(),compile(),complex(),delattr(),dict()
dir(),divmod(),enumerate(),eval(),exec(),filter(),float(),format(),frozenset(),getattr()
globals(),hasattr(),hash(),help(),hex(),id(),input(),int(),isinstance(),issubclass()
iter(),len(),list(),locals(),map(),max(),memoryview(),min(),next(),object(),oct()
open(),ord(),pow(),print(),property(),range(),repr(),reversed(),round(),set(),setattr()
slice(),sorted(),staticmethod(),str(),sum(),super(),tuple(),type(),vars(),zip(),__import__()
具体的使用可以参考https://docs.python.org/zh-cn/3/library/functions.html
二、内置常量:
有少数的常量存在于内置命名空间中,如:True  False   None  NotImplemented   Ellipsis __debug__ 
site模块添加的常量:quit  exit  copyright  credits  license
三、操作系统接口:
os模块提供了不少与操作系统相关联的函数。
>>> import os
>>> os.getcwd()      # 返回当前的工作目录
'C:\\Python36'
>>> os.chdir('/server/accesslogs')   # 修改当前的工作目录
>>> os.system('mkdir today')   # 执行系统命令 mkdir

>>> dir(os)#查看os模块中的子模块
<returns a list of all module functions>
>>> help(os)#查看os的描述文档
<returns an extensive manual page created from the module's docstrings>
针对日常的文件和目录管理任务,:mod:shutil 模块提供了一个易于使用的高级接口
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
>>> shutil.move('/build/executables', 'installdir')
四、文件通配符:
glob模块提供了一个函数用于从目录通配符搜索中生成文件列表
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
五、命令行参数:
通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。
>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']
六、错误输出重定向和程序终止:
sys 还有 stdin,stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以用于显示警告和错误信息。
>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
大多脚本的定向终止都使用 "sys.exit()"。
七、字符串正则匹配:
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'
八、数学模块:
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)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # random float
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4
statistics提供数学统计函数
from statistics import median,mean
data = [20.7, 11.4,19.2, 18.3, 23.1, 14.4]
print('数据的中位数(中间值)是:',median(data))
print('数据的算数平均值是:',mean(data))
结果:
数据的中位数(中间值)是: 18.75
数据的算数平均值是: 17.85
九、互联网访问:
有几个模块用于访问互联网以及处理网络通信协议。其中最简单的两个是用于处理从 urls 接收的数据的 urllib.request 以及用于发送电子邮件的 smtplib:
>>> from urllib.request import urlopen
>>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
...     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)

<BR>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()
十、日期和时间:
datetime模块为日期和时间处理同时提供了简单和复杂的方法。
支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。
常用时间处理方法
今天 today = datetime.date.today()
昨天 yesterday = today - datetime.timedelta(days=1)
上个月 last_month = today.month - 1 if today.month - 1 else 12
当前时间戳 time_stamp = time.time()
时间戳转datetime datetime.datetime.fromtimestamp(time_stamp)
datetime转时间戳 int(time.mktime(today.timetuple()))
datetime转字符串 today_str = today.strftime("%Y-%m-%d")
字符串转datetime today = datetime.datetime.strptime(today_str, "%Y-%m-%d")
补时差 today + datetime.timedelta(hours=8)
更多关于python标准库的使用可以参考python官方文档https://docs.python.org/zh-cn/3/library/index.html。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

春风抚微霞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值