《Python Cookbook》读书笔记

廉价感情. 提交于 2021-01-02 16:14:36

2.3 Matching Strings Using Shell Wildcard Patterns

from fmatch import fnmatch, fnmatchcase

#coding=utf-8
'''
Matching Strings Using Shell Wildcard Patterns:
from fmatch import fnmatch, fnmatchcase
'''

from fnmatch import fnmatch, fnmatchcase
a = fnmatch('too.txt', '*.txt')
b = fnmatch('foo.txt', '?oo.txt')
c = fnmatch('Dat45.csv', 'Dat[0-9]*')
print(a)
print(b)
print(c)

names = ['Dat1.csv', 'Dat2.csv', 'config.ini', 'foo.py']
# 选以Dat开头的csv文件
d = [name for name in names if fnmatch(name, 'Dat*.csv')]
print(d)

# fnmatch是否区分大小写 与 本机操作系统一致
e = fnmatch('foo.txt', '*.TXT')
print(e)
f = fnmatchcase('foo.txt', '*.TXT')
print(f)

addresses = [
    '5412 N CLARK ST',
    '1060 W ADDISON ST',
    '1039 W GRANVILLE AVE',
    '2122 N CLARK ST',
    '4802 N BROADWAY',
]

# 以ST结尾的
g = [address for address in addresses if fnmatch(address, '*ST')]
# 54开头 包含CLARK
h = [address for address in addresses if fnmatchcase(address, '54[0-9][0-9] *CLARK*')]
print(g)
print(h)

2.4. Matching and Searching for Text Patterns

import re
The essential functionality is first compiling a pattern using
re.compile() and then using methods such as match() , findall() , or finditer()

#coding=utf-8
'''
2.4. Matching and Searching for Text Patterns:
 use regular expressions and the  re module
 import re

 The essential functionality is first compiling a pattern using
re.compile() and then using methods such as  match() ,  findall() , or  finditer()

'''
# match dates specified as digits, such as “11/27/2012.”
test1 = '11/27/2012'
test2 = 'Nov 27, 2012'
import re
if re.match(r'\d+/\d+/\d+', test1):  # \d+ means match one or more digits
    print('yes')
else:
    print('no')

# If you’re going to perform a lot of matches using the same pattern, it usually pays to
# precompile the regular expression pattern into a pattern object first
datepat = re.compile(r'\d+/\d+/\d+')
if datepat.match(test1):
    print('yes')
else:
    print('no')

if datepat.match(test2):
    print('yes')
else:
    print('no')

# match(): find the first
# findall(): find all
test = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
a = datepat.findall(test)
print(a)

datpat2 = re.compile(r'(\d+)/(\d+)/(\d+)')
m = datpat2.match('11/27/2012')
print(m)
b = m.group(0)
c = m.group(1)
d = m.group(2)
e = m.groups()
print(b)
print(c)
print(d)
print(e)
month, day, year = m.groups()
print(month)

print(test)
f = datpat2.findall(test)
print(f)
for month, day, year in datpat2.findall(test):
    print('{}-{}-{}'.format(year, month, day))

# The  findall() method searches the text and finds all matches, returning them as a list.
# If you want to find matches iteratively, use the  finditer() method instead
for m in datpat2.finditer(test):
    print(m.groups())

# If you want an exact match, make sure the pattern includes the end-marker ( $ )

n = datepat.match('11/27/2012abcdef')
datepat3 = re.compile(r'\d+/\d+/\d+$')
datepat4 = re.compile(r'(\d+)/(\d+)/(\d+)$')
i = datepat4.match('11/27/2012abcdef')
j = datepat4.match('11/27/2012')
print(i)
print(j)

# module-level functions**
re.findall(r'(\d+)/(\d+)/(\d+)', tes**********t)
# (Be aware, though, that if you’re going to perform a lot of matching or searching, it usually
# pays to compile the pattern first and use it over and over again. The module-level func‐
# tions keep a cache of recently compiled patterns, so there isn’t a huge performance hit,
# but you’ll save a few lookups and extra processing by using your own compiled pattern.)

3.4 将Integer转换成 2/8/16进制数

  1. bin()、oct()、hex()
>>> x = 1234
>>> bin(x)
'0b10011010010'
>>> oct(x)
'0o2322'
>>> hex(x)
'0x4d2'    

# 操作负数
>>> x = -1234
>>> format(x, 'b')
'-10011010010'
>>> format(x, 'x')
'-4d2'
  1. format(). 可以不显示开头的0
>>> format(x, 'b')
'10011010010'
>>> format(x, 'o')
'2322'
>>> format(x, 'x')
'4d2'
  1. 转回来(即不同进制数 转换成 整数),用 int()
>>> int('4d2', 16)
1234
>>> int('10011010010', 2)
1234
  1. 注意:Python中,识别/指定八进制数 是0o, 不是0.
>>> import os
>>> os.chmod('script.py', 0755)
File "<stdin>", line 1
os.chmod('script.py', 0755)
^
SyntaxError: invalid token

改成如下写法,即不会报错。

>>> os.chmod('script.py', 0o755)

最后,注意:
大多数情况下处理二进制、八进制和十六进制整数是很简单的。只要记住这些转换属于整数和其对应的文本表示之间的转换即可。永远只有一种整数类型。

3.5 字节到大整数的打包与解包

1)bytes -> large integer value: 用 int.from_bytes() 方法。
2)large integer value -> bytes: 用 int.to_bytes() 方法。

data = b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004'
>>> int.from_bytes(data, 'little')
69120565665751139577663547927094891008
>>> int.from_bytes(data, 'big')
94522842520747284487117727783387188

>>> x = 94522842520747284487117727783387188
>>> x.to_bytes(16, 'big')
b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004'
>>> x.to_bytes(16, 'little')
b'4\x00#\x00\x01\xef\xcd\x00\xab\x90x\x00V4\x12\x00'

3)字节顺序规则 (little 或 big) 仅仅指定了构建整数时的字节的低位高位排列方式。

>>> x = 0x01020304
>>> x.to_bytes(4, 'big')
b'\x01\x02\x03\x04'
>>> x.to_bytes(4, 'little')
b'\x04\x03\x02\x01'

3.6 复数 的数学运算

  1. 使用函数 complex(real, imag) 或者是带有后缀 **j **的浮点数来指定
>>> a = complex(2, 4)
>>> b = 3 - 5j
>>> a
(2+4j)
>>> b
(3-5j)
  1. 实部、虚部、共轭复数
>>> a.real
2.0
>>> a.imag
4.0
>>> a.conjugate()
(2-4j)
  1. 所有常见的数学运算都可以工作, 如果要执行其他的复数函数比如正弦、余弦或平方根,使用 cmath 模块
>>> a + b
(5-1j)
>>> a * b
(26+2j)
>>> a / b
(-0.4117647058823529+0.6470588235294118j)
>>> abs(a)
4.47213595499958

>>> import cmath
>>> cmath.sin(a)
(24.83130584894638-11.356612711218174j)
>>> cmath.cos(a)
(-11.36423470640106-24.814651485634187j)
>>> cmath.exp(a)
(-4.829809383269385-5.5920560936409816j)
  1. Python 中大部分与数学相关的模块都能处理复数。比如如果你使用 numpy ,可以 很容易的构造一个复数数组并在这个数组上执行各种操作
  2. Python 的标准数学函数确实情况下并不能产生复数值,因此你的代码中不可能会 出现复数返回值。
    如果你想生成一个复数返回结果,你必须显示的使用 cmath 模块,或者在某个支 持复数的库中声明复数类型的使用。
>>> import cmath
>>> cmath.sqrt(-1)
1j

3.7 无穷大与 NaN (not a number)

  1. 创建。
    Python 并没有特殊的语法来表示这些特殊的浮点值,可以使用 float() 来创建它们
>>> a = float('inf')
>>> b = float('-inf')
>>> c = float('nan')
>>> a
inf
>>> b
-inf
>>> c
nan
  1. 为了测试这些值的存在,使用 math.isinf() 和 **math.isnan()**函数
>>> math.isinf(a)
True
>>> math.isinf(b)
True
>>> math.isnan(c)
True
>>

3_1) 无穷大数在执行数学计算的时候会传播

>>> a = float('inf')
>>> a + 45
inf
>>> a * 10
inf
>>> 10 / a
0.0

3_2) 有些未定义的操作并会返回一个 NaN 结果

>>> a = float('inf')
>>> a/a
nan
>>> b = float('-inf')
>>> a + b
nan

3_3) NaN 值会在所有操作中传播,而不会产生异常。

>>> c = float('nan')
>>> c + 23
nan
>>> c / 2
nan
>>> c * 2
nan
>>> math.sqrt(c)
nan

3_4) NaN 值的一个特别的地方时它们之间的比较操作总是返回 False

>>> c = float('nan')
>>> d = float('nan')
>>> c == d
False
>>> c is d
False
  1. 有时候程序员想改变 Python 默认行为,在返回无穷大或 NaN 结果的操作中抛出 异常。 fpectl 模块可以用来改变这种行为,但是它在标准的 Python 构建中并没有被 启用,它是平台相关的,并且针对的是专家级程序员。

3.8 分数运算

  1. 使用 fractions 模块
>>> from fractions import Fraction
>>> a = Fraction(5, 4)
>>> b = Fraction(7, 16)
>>> print(a + b)
27/16
>>> # Getting numerator/denominator
>>> c = a * b
>>> c.numerator    # 分子
35
>>> c.denominator  # 分母
64

>>> # Converting to a float
>>> float(c)

>>> # Limiting the denominator of a value
>>> print(c.limit_denominator(8))

>>> # 将小数转成分数
>>> x = 3.75
>>> y = Fraction(*x.as_integer_ratio())
>>> y
Fraction(15, 4)
  1. 这个虽然少用,但是有时直接使用分数可以减少手动转换为小数或浮点数的工作。
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!