14-22章主要介绍了这几个内容
- 使用正则表达式
- ASCII对文本字符编码
- 解析CSV
- 生成带有提示类型的交互版本
一、使用正则表达式
正则表达式是一种用于匹配和处理文本的强大工具,它通过定义一种特定的语法规则,可以用来搜索、替换、提取或验证字符串中的特定模式
书中举出的例子是对输入的单词,提取前缀和词干,如果使用普通的for循环也是可以查找,但是使用正则,可以更高效的匹配到想要的字符串
def main():
args = get_args()
prefixes = list('bcdfghjklmnpqrstvwxyz') + (
'bl br ch cl cr dr fl fr gl gr pl pr sc '
'sh sk sl sm sn sp st sw th tr tw thw wh wr '
'sch scr shr sph spl spr squ str thr').split()
start, rest = stemmer(args.word)
if rest:
print('\n'.join(sorted([p + rest for p in prefixes if p != start])))
else:
print(f'Cannot rhyme "{args.word}"')
def stemmer(word):
word = word.lower()
vowels = 'aeiou'
consonants = ''.join(
[c for c in string.ascii_lowercase if c not in vowels])
pattern = (
'([' + consonants + ']+)?'
'([' + vowels + '])'
'(.)'
)
pattern = f'([{consonants}]+)?([{vowels}])(.)'
match = re.match(pattern, word)
if match:
p1 = match.group(1) or ''
p2 = match.group(2) or ''
p3 = match.group(3) or ''
return (p1, p2 + p3)
else:
return (word, '')
介绍一下python中正则表达式的用法
import re
match = re.match(pattern, word)
match.group()


二、ASCII对文本字符编码
介绍了python中是如何处理字符编码的
1. ord()
用于字符和Unicode码点之间的转换
print(ord('A'))
print(ord('a'))
print(ord('中'))
2. chr()
与ord()相反,用于将Unicode码点转换为字符
print(chr(65))
print(chr(97))
print(chr(20013))

3. re.sub()
用于在字符串中查找匹配正则表达式的部分,并将其替换为指定的内容,用于字符串的复杂替换操作
import re
result = re.sub(r'\d', '', 'abc123xyz')
print(result)
result = re.sub(r'\s', '-', 'Hello World')
print(result)
三、解析CSV
python也经常用于数据处理,所以和csv文件交互式很常见的内容,下面展示了如何简单的读取一个csv文件
with open('inputs/exercises.csv') as fh:
headers = fh.readline().rstrip().split(',')
records = []
for line in fh:
rec = dict(zip(headers, line.rstrip().split(',')))
records.append(rec)
下面图中是书中展示了如何使用zip处理文件

四、一些小技巧
书的最后编写了一个井字棋游戏,主要使用到了之前介绍了语法,通过一个实践的例子加深读者对python的使用
代码编写过程中还有一些小的语法知识点:
1. enumerate()代替list的索引和值
enumerate()是Python内置函数,用于在遍历列表(或其他可迭代对象)时同时获取元素的索引和值它避免了手动管理索引变量,使代码更简洁
fruits = ['apple', 'banana', 'cherry']
for index, value in enumerate(fruits):
print(f"Index:{index}, Value:{value}")
2. TypedDict类
TypedDict是Python3.8引入的一个类型注解工具,用于定义字典的结构和类型,它可以帮助你在静态类型检查时确保字典的键和值符合预期的类型
TypedDict主要用于静态类型检查(如使用mypy),不会在运行时强制类型约束
from typing import TypedDict
class Person(TypedDict):
name:str
age:int
person:Person = {
'name':'Alice',
'age':30
}
3. mypyt分析类型错误
mypy是一个静态类型检查工具,用于在Python代码中检查类型注解的正确性,可以帮助你在开发阶段发现类型错误,提高代码的健壮性,它支持Python3.5及以上版本的类型注解功能
def greet(name:str) -> str:
return f"Hello, {name}"
greet(42)
mypy example.py
总结
- 本书中作者用了很多的国外的文化故事,为了加强读者的理解,但是由于文化背景的隔阂,所以作为中文读者,没办法理解的这么深,但是能大概从例子中看到python的使用方法,还是不错的。但是在后面的章节中,甚至语法可以理解,但是文章开头的故事需要更多理解一下。
- 作者虽然将书本分了章节,有时候章节会互相穿插,比如后面csv章节,还穿插了list(zip())语法的解释,我比较喜欢将相关的知识做归类,阅读这本书,就得自己归类了。但是相反的,穿插了各种语法的使用方法,可以加深理解
- 总体而言,这是一本python初学者入门时可以阅读的读物,通过例子,是可以了解到一些实际python的使用场景,而不是仅仅知道一些简单的语法