Python基础语法-菜鸟教程-第23章:Python3 标准库概览

学习网址:https://www.runoob.com/python/python-basic-syntax.html
运行代码后即可生成笔记

未完成部分:各种方法未动手实践操作

#代码如下:

import sys
# chapter23:Python3 标准库概览
print("\nchapter23:Python3 标准库概览\n")
print("1.操作系统接口")
print("1)os模块提供了不少与操作系统相关联的函数。")
print("eg:")
print(">>> import os\n"
">>> os.getcwd()      # 返回当前的工作目录\n"
"'C:\\Python34'\n"
">>> os.chdir('/server/accesslogs')   # 修改当前的工作目录\n"
">>> os.system('mkdir today')   # 执行系统命令 mkdir \n"
"0")
print("2)在使用 os 这样的大型模块时内置的 dir() 和 help() 函数非常有用:")
print("eg:")
print(">>> import os\n"
">>> dir(os)\n"
"\n"
">>> help(os)\n"
"")
print("3)针对日常的文件和目录管理任务,:mod:shutil 模块提供了一个易于使用的高级接口")
print("eg:")
print(">>> import shutil\n"
">>> shutil.copyfile('data.db', 'archive.db')\n"
">>> shutil.move('/build/executables', 'installdir')")
print("2.文件通配符")
print("1)glob模块提供了一个函数用于从目录通配符搜索中生成文件列表")
print("eg:")
print(">>> import glob\n"
">>> glob.glob('*.py')\n"
"['primes.py', 'random.py', 'quote.py']")
print("3.命令行参数")
print("1)通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。")
print("eg:例如在命令行中执行 \"python demo.py one two three\" 后可以得到以下输出结果:")
print(">>> import sys\n"
">>> print(sys.argv)\n"
"['demo.py', 'one', 'two', 'three']")
print("4.错误输出重定向和程序终止")
print("1)sys 还有 stdin,stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以用于显示警告和错误信息。")
print("eg:")
print(">>> sys.stderr.write('Warning, log file not found starting a new one\n')\n"
"Warning, log file not found starting a new one")
print("2)大多脚本的定向终止都使用 \"sys.exit()\"。")
print("5.字符串正则匹配")
print("1)re模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案:")
print("eg:")
print(">>> import re\n"
">>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')\n"
"['foot', 'fell', 'fastest']\n"
">>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')\n"
"'cat in the hat'")
print("2)如果只需要简单的功能,应该首先考虑字符串方法,因为它们非常简单,易于阅读和调试:")
print("eg:")
print(">>> 'tea for too'.replace('too', 'two')\n"
"'tea for two'")
print("6.数学")
print("1)math模块为浮点运算提供了对底层C函数库的访问:")
print("eg:")
print(">>> import math\n"
">>> math.cos(math.pi / 4)\n"
"0.70710678118654757\n"
">>> math.log(1024, 2)\n"
"10.0")
print("2)random提供了生成随机数的工具。")
print("eg:")
print(">>> import random\n"
">>> random.choice(['apple', 'pear', 'banana'])\n"
"'apple'\n"
">>> random.sample(range(100), 10)   # sampling without replacement\n"
"[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]\n"
">>> random.random()    # random float\n"
"0.17970987693706186\n"
">>> random.randrange(6)    # random integer chosen from range(6)\n"
"4")
print("7.访问 互联网")
print("1)有几个模块用于访问互联网以及处理网络通信协议。其中最简单的两个是用于处理从 urls 接收的数据的 urllib.request 以及用于发送电子邮件的 smtplib:")
print("eg:")
print(">>> from urllib.request import urlopen\n"
">>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):\n"
"...     line = line.decode('utf-8')  # Decoding the binary data to text.\n"
"...     if 'EST' in line or 'EDT' in line:  # look for Eastern Time\n"
"...         print(line)\n"

"
Nov. 25, 09:43:32 PM EST\n"
">>> import smtplib\n" ">>> server = smtplib.SMTP('localhost')\n" ">>> server.sendmail('[email protected]', '[email protected]',\n" "... \"\"\"To: [email protected]\n" "... From: [email protected]\n" "...\n" "... Beware the Ides of March.\n" "... \"\"\")\n" ">>> server.quit()") print("8.日期和时间") print("1)datetime模块为日期和时间处理同时提供了简单和复杂的方法。\n" "2)支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。\n" "3)该模块还支持时区处理:") print("eg:") print(">>> # dates are easily constructed and formatted\n" ">>> from datetime import date\n" ">>> now = date.today()\n" ">>> now\n" "datetime.date(2003, 12, 2)\n" ">>> now.strftime(\"%m-%d-%y. %d %b %Y is a %A on the %d day of %B.\")\n" "'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'\n" ">>> # dates support calendar arithmetic\n" ">>> birthday = date(1964, 7, 31)\n" ">>> age = now - birthday\n" ">>> age.days\n" "14368") print("9.数据压缩") print("1)以下模块直接支持通用的数据打包和压缩格式:zlib,gzip,bz2,zipfile,以及 tarfile。") print("eg:") print(">>> import zlib\n" ">>> s = b'witch which has which witches wrist watch'\n" ">>> len(s)\n" "41\n" ">>> t = zlib.compress(s)\n" ">>> len(t)\n" "37\n" ">>> zlib.decompress(t)\n" "b'witch which has which witches wrist watch'\n" ">>> zlib.crc32(s)\n" "226805979") print("10.性能度量") print("1)有些用户对了解解决同一问题的不同方法之间的性能差异很感兴趣。Python 提供了一个度量工具,为这些问题提供了直接答案。timeit ") print("11.测试模块") print("1)开发高质量软件的方法之一是为每一个函数开发测试代码,并且在开发过程中经常进行测试\n" "2)doctest模块提供了一个工具,扫描模块并根据程序中内嵌的文档字符串执行测试。\n" "3)测试构造如同简单的将它的输出结果剪切并粘贴到文档字符串中。\n" "4)通过用户提供的例子,它强化了文档,允许 doctest 模块确认代码的结果是否与文档一致:") print("eg:") print("def average(values):\n" " \"\"\"Computes the arithmetic mean of a list of numbers.\n" " >>> print(average([20, 30, 70])) \n" " 40.0\n" " \"\"\"\n" " return sum(values) / len(values)\n" "import doctest\n" "doctest.testmod() # 自动验证嵌入测试") print("5)unittest模块不像 doctest模块那么容易使用,不过它可以在一个独立的文件里提供一个更全面的测试集:") print("eg:") print("import unittest\n" "class TestStatisticalFunctions(unittest.TestCase):\n" " def test_average(self):\n" " self.assertEqual(average([20, 30, 70]), 40.0)\n" " self.assertEqual(round(average([1, 5, 7]), 1), 4.3)\n" " self.assertRaises(ZeroDivisionError, average, [])\n" " self.assertRaises(TypeError, average, 20, 30, 70)\n" "unittest.main() # Calling from the command line invokes all tests")

#代码运行结果如下:

chapter23:Python3 标准库概览

1.操作系统接口
1)os模块提供了不少与操作系统相关联的函数。
eg:

import os
os.getcwd() # 返回当前的工作目录
‘C:\Python34’

os.chdir(’/server/accesslogs’) # 修改当前的工作目录
os.system(‘mkdir today’) # 执行系统命令 mkdir
0
2)在使用 os 这样的大型模块时内置的 dir() 和 help() 函数非常有用:
eg:

import os
dir(os)

help(os)

3)针对日常的文件和目录管理任务,:mod:shutil 模块提供了一个易于使用的高级接口
eg:

import shutil
shutil.copyfile(‘data.db’, ‘archive.db’)
shutil.move(’/build/executables’, ‘installdir’)
2.文件通配符
1)glob模块提供了一个函数用于从目录通配符搜索中生成文件列表
eg:

import glob
glob.glob(’*.py’)
[‘primes.py’, ‘random.py’, ‘quote.py’]
3.命令行参数
1)通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。
eg:例如在命令行中执行 “python demo.py one two three” 后可以得到以下输出结果:

import sys
print(sys.argv)
[‘demo.py’, ‘one’, ‘two’, ‘three’]
4.错误输出重定向和程序终止
1)sys 还有 stdin,stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以用于显示警告和错误信息。
eg:

sys.stderr.write('Warning, log file not found starting a new one
')
Warning, log file not found starting a new one
2)大多脚本的定向终止都使用 “sys.exit()”。
5.字符串正则匹配
1)re模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案:
eg:

import re
re.findall(rf[a-z]*’, ‘which foot or hand fell fastest’)
[‘foot’, ‘fell’, ‘fastest’]

re.sub(r’[a-z]+) ’, r’’, ‘cat in the the hat’)
‘cat in the hat’
2)如果只需要简单的功能,应该首先考虑字符串方法,因为它们非常简单,易于阅读和调试:
eg:

‘tea for too’.replace(‘too’, ‘two’)
‘tea for two’
6.数学
1)math模块为浮点运算提供了对底层C函数库的访问:
eg:

import math
math.cos(math.pi / 4)
0.70710678118654757

math.log(1024, 2)
10.0
2)random提供了生成随机数的工具。
eg:

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
7.访问 互联网
1)有几个模块用于访问互联网以及处理网络通信协议。其中最简单的两个是用于处理从 urls 接收的数据的 urllib.request 以及用于发送电子邮件的 smtplib:
eg:

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)

Nov. 25, 09:43:32 PM EST

import smtplib
server = smtplib.SMTP(‘localhost’)
server.sendmail(‘[email protected]’, ‘[email protected]’,
… “”“To: [email protected]
… From: [email protected]

… Beware the Ides of March.
… “””)

server.quit()
8.日期和时间
1)datetime模块为日期和时间处理同时提供了简单和复杂的方法。
2)支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。
3)该模块还支持时区处理:
eg:

dates are easily constructed and formatted

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.’

dates support calendar arithmetic

birthday = date(1964, 7, 31)
age = now - birthday
age.days
14368
9.数据压缩
1)以下模块直接支持通用的数据打包和压缩格式:zlib,gzip,bz2,zipfile,以及 tarfile。
eg:

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.性能度量
1)有些用户对了解解决同一问题的不同方法之间的性能差异很感兴趣。Python 提供了一个度量工具,为这些问题提供了直接答案。timeit
11.测试模块
1)开发高质量软件的方法之一是为每一个函数开发测试代码,并且在开发过程中经常进行测试
2)doctest模块提供了一个工具,扫描模块并根据程序中内嵌的文档字符串执行测试。
3)测试构造如同简单的将它的输出结果剪切并粘贴到文档字符串中。
4)通过用户提供的例子,它强化了文档,允许 doctest 模块确认代码的结果是否与文档一致:
eg:
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() # 自动验证嵌入测试
5)unittest模块不像 doctest模块那么容易使用,不过它可以在一个独立的文件里提供一个更全面的测试集:
eg:
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)
self.assertRaises(ZeroDivisionError, average, [])
self.assertRaises(TypeError, average, 20, 30, 70)
unittest.main() # Calling from the command line invokes all tests

你可能感兴趣的:(python基础)