play-Python
start to study python from 《Python 快速入门》(第3版)
1、基础知识
- 缩进、代码块构建:使用缩进、不用大括号
- 注释:#
- 变量、赋值:不是容器、标签
- 表达式:// 整除
- 字符串:
"abc"
、'abc'
、"""abc"""
- 数值:
- 整数可为任意大小
- 函数
- 内置处理函数:abs、divmod、float、hex、int、max、min、oct、pow、round
- 高级(math模块):acos、asin、atan、atan2、ceil、cos、cosh、e、exp、fabs、floor、fmod、frexp、hypot、ldexp、log、log10、mod、pi、pow、sin、sinh、sqrt、tan、tanh
- 复数计算
- 复数函数(cmath模块):acos、acosh、asin、asinh、atan、atanh、cos、cosh、e、exp、log、log10、pi、sin、sinh、sqrt、tan、tanh
- Python中科学计算的基本算法
- None
- input 输入
- 操作符
- 编码风格:Python增强提案8(Python Enhancement Proposal 8,PEP 8)
2、列表、元组、集合
- 列表
- 索引、修改、排序、其他操作、深拷贝
- 元组
- 集合
3、字符串
- 索引、切片、拼接、转义字符、
- 其他方法:join、split、转换为数值、strip去除空白符(lstrip、rstrip)、find搜索(rfind)、startswith、endswith、replace替换、maketrans多个字符对应替换translate、等等
- 其他操作:repr对象转为字符串、格式化字符串format(新)、用%格式化字符串(旧)、encode
4、字典
- 字典获取 keys、values、items、
- get获取对应key的值、setdefault设置默认值、
- copy拷贝一个字典、update更新合并、
- 稀疏矩阵、用作缓存
5、流程控制
- if elseif else
- for循环:range函数、元组拆包、enumerate、zip合并
- 列表推导式
[]
、字典推导式{}
、生成器表达式()
and
or
is
==
!=
not
6、函数
- def、参数、形参、默认值、
- 实参
- 参数数量不定:*(返回元组)、**(返回字典)、
- 对象用作函数实参
- 全局变量global、非局部变量nonlocal
- lambda、Generator、Decorators
7、模块
- import mymath
- from mymath import pi
- 命名空间
- locals() 当前全局作用域的变量名和值字典
- globals() 前局部作用域的变量名和值字典
- dir()返回给定模块中定义的对象名称列表
8、程序
- sys.argv
- from argparse import ArgumentParser
- sys.stdin.read()、sys.stdout.write()
- import fileinput
- def main():python
if __name__ == "__main__": main()
9、文件系统的使用
- os(旧):
- os.getcwd 当前工作目录、os.listdir 列出目录内容、os.curdir 当前目录
- os.path.join 路径拼接、os.path.split 路径拆分、os.path.basename 文件名、os.path.dirname 父目录、os.path.splitext 文件后缀、os.path.commonprefix 公共前缀、os.path.isabs 是否是绝对路径
- os.path.exists 是否存在、os.path.isdir 是否是目录、os.path.isfile 是否是文件、os.path.getsize 文件大小、os.path.islink 是否是符号链接
- glob.glob("*") 匹配所有文件
- os.walk 递归遍历目录
- pathlib(新):
cur_path = pathlib.Path()
- cur_path.cwd() 当前工作目录、cur_path.joinpath 路径拼接、cur_path / "bin" 路径拼接
- cur_path.parts 路径拆分、cur_path.name 文件名、cur_path.parent 父目录、cur_path.suffix 文件后缀
- cur_path.resolve() 绝对路径、cur_path.iterdir()路径迭代器 、cur_path.glob() 匹配所有文件
- cur_path.is_file() 是否是文件、cur_path.is_symlink() 是否是符号链接
10、文件的读写
- 打开文件、关闭文件、写入文件、二进制
- pathlib Path对象来读写文本和二进制文件、使用简便(无法追加)
- 屏幕输入、输出
- 重定向:
- sys.stdin.readline、
- sys.stdout.write、
f = open("outfile.txt", "w") sys.stdout = f
- struct 二进制数据的读写(要处理的文件是由其他程序生成或使用的)
- pickle 任何数据结构写入文件,再从文件中读回并重建该数据结构
- shelve 字典,存储在磁盘,通过键来访问数据,不受内存大小的限制
11、异常处理
- 异常类型
- raise 抛出异常
- try except else finally 捕捉、处理异常
- 自定义异常
- assert 断言
- 正常计算过程中的异常
- with 上下文管理器
查看代码
- 1
查看代码 input
py
# 整数不允许输入浮点数
int(input("?"))
# ?22.2
# Traceback (most recent call last):
# File "<pyshell#3>", line 1, in <module>
# int(input(1))
# ValueError: invalid literal for int() with base 10: '22.2'
# 整数允许输入整数
int(input("?"))
# ?22
# 22
# 浮点数允许输入浮点数
float(input("?"))
# ?2222.22
# 2222.22
# 浮点数允许输入整数
float(input("?"))
# ?222
# 222.0
查看代码 number
py
# 内置:abs、divmod、float、hex、int、max、min、oct、pow、round
# 高级(math模块):acos、asin、atan、atan2、ceil、cos、cosh、e、exp、fabs、floor、fmod、frexp、hypot、ldexp、log、log10、mod、pi、pow、sin、sinh、sqrt、tan、tanh
# 复数函数(cmath模块):acos、acosh、asin、asinh、atan、atanh、cos、cosh、e、exp、log、log10、pi、sin、sinh、sqrt、tan、tanh
# 乘法
"2.2" * 2
# '2.22.2'
"123"*2
# '123123'
"12.2" * 2.2
# Traceback (most recent call last):
# File "<pyshell#7>", line 1, in <module>
# "12.2" * 2.2
# TypeError: can't multiply sequence by non-int of type 'float'
"12" * 2.2
# Traceback (most recent call last):
# File "<pyshell#8>", line 1, in <module>
# "12" * 2.2
# TypeError: can't multiply sequence by non-int of type 'float'
"12" * 2+1j
# Traceback (most recent call last):
# File "<pyshell#9>", line 1, in <module>
# "12" * 2+1j
# TypeError: can only concatenate str (not "complex") to str
"12" * (2+1j)
# Traceback (most recent call last):
# File "<pyshell#10>", line 1, in <module>
# "12" * (2+1j)
# TypeError: can't multiply sequence by non-int of type 'complex'
# 加法
"123" + 1
# Traceback (most recent call last):
# File "<pyshell#11>", line 1, in <module>
# "123"+1
# TypeError: can only concatenate str (not "int") to str
"12"+1.1
# Traceback (most recent call last):
# File "<pyshell#12>", line 1, in <module>
# "12"+1.1
# TypeError: can only concatenate str (not "float") to str
"12"+(2+1j)
# Traceback (most recent call last):
# File "<pyshell#13>", line 1, in <module>
# "12"+(2+1j)
# TypeError: can only concatenate str (not "complex") to str
# 除法
"123" /2
# Traceback (most recent call last):
# File "<pyshell#14>", line 1, in <module>
# "123" /2
# TypeError: unsupported operand type(s) for /: 'str' and 'int'
"123" /2.2
# Traceback (most recent call last):
# File "<pyshell#15>", line 1, in <module>
# "123" /2.2
# TypeError: unsupported operand type(s) for /: 'str' and 'float'
- 2
查看代码 list
py
# 列表
# 列表长度
len([])
# 0
len([0])
# 1
len([[1, 2, 3, 3], 7])
# 索引
# 1、正向索引
x = ["first", "second", "third", "fourth"]
print(x[1:-1])
# ['second', 'third']
print(x[0:3])
# ['first', 'second', 'third']
print(x[-2:-1])
# ['third']
# 2、反向索引
print(x[-1:2])
# []
# 3、省略索引
print(x[:3])
# ['first', 'second', 'third']
print(x[2:])
# ['third', 'fourth']
y = x[:]
y[0] = "1 st"
print(y)
# ['1 st', 'second', 'third', 'fourth']
print(x)
# ['first', 'second', 'third', 'fourth']
# 编辑列表
# 1、替换
# 单个元素替换
x = [1, 2, 3, 4]
x[1] = "two"
print(x)
# [1, 'two', 3, 4]
# 多个元素替换
x = [1, 2, 3, 4]
x[1:3] = ["two", "three"]
print(x)
# [1, 'two', 'three', 4]
x[1:3] = ["two"]
print(x)
# [1, 'two', 4]
# 字符串替换
x = [1, 2, 3, 4]
x[1:3] = "123"
print(x)
# [1, '1', '2', '3', 4]
# 2、添加
# 在列表末尾添加元素
x = [1, 2, 3, 4]
x[len(x) :] = [5, 6, 7]
print(x)
# [1, 2, 3, 4, 5, 6, 7]
# 在列表头部添加元素
x = [1, 2, 3, 4]
x[:0] = [-1, 0]
print(x)
# [-1, 0, 1, 2, 3, 4]
# append
x = [1, 2, 3]
x.append("four")
print(x)
# [1, 2, 3, 'four']
x = [1, 2, 3, 4]
y = [5, 6, 7]
x.append(y)
print(x)
# [1, 2, 3, 4, [5, 6, 7]]
# extend
x = [1, 2, 3, 4]
y = [5, 6, 7]
x.extend(y)
print(x)
# [1, 2, 3, 4, 5, 6, 7]
# insert
# list.insert(n, elem)与list[n:n] = [elem]的效果是一样的。
x = [1, 2, 3]
x.insert(2, "hello")
print(x)
# [1, 2, 'hello', 3]
x.insert(0, "start")
print(x)
# ['start', 1, 2, 'hello', 3]
x = [1, 2, 3]
x.insert(-1, "hello")
print(x)
# [1, 2, 'hello', 3]
# 3、删除
# 删除多个元素
x = [1, 2, 3, 4]
x[1:3] = []
print(x)
# [1, 4]
# 删除列表
x = [1, 2, 3, 4]
x[:] = []
print(x)
# []
# del
# del list[n]的功能与list[n:n+1] = []是一样的
# 而del list[m:n]的功能则与list[m:n] = []相同
x = ["a", 2, "c", 7, 9, 11]
del x[1]
print(x)
# ['a', 'c', 7, 9, 11]
del x[:2]
print(x)
# [7, 9, 11]
# remove 删除的是列表中的元素
x = [1, 2, 3, 4, 3, 5]
x.remove(3)
print(x)
# [1, 2, 4, 3, 5]
x.remove(3)
print(x)
# [1, 2, 4, 5]
# x.remove(3)
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# ValueError: list.remove(x): x not in list
# 4、反转列表
x = [1, 3, 5, 6, 7]
x.reverse()
print(x)
# [7, 6, 5, 3, 1]
# 列表移动至表头
# 切片插入
data_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
last_three = data_list[-3:] # 获取最后 3 个数据项
del data_list[-3:] # 从原列表中删除最后 3 个数据项
data_list[0:0] = last_three # 将最后 3 个数据项插入到列表开头
print(data_list)
# 循环插入 pop 和 insert
data_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for _ in range(3):
item = data_list.pop() # 移除列表末尾的元素
data_list.insert(0, item) # 将元素插入到列表开头
print(data_list)
查看代码 list_sort
py
# 排序
# x = [1, 2, 'hello', 3]
# x.sort()
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: '<' not supported between instances of 'str' and 'int'
# 列表的列表
x = [[3, 5], [2, 9], [2, 3], [4, 1], [3, 2]]
x.sort()
print(x)
# [[2, 3], [2, 9], [3, 2], [3, 5], [4, 1]]
# 自定义排序
def compare_num_of_chars(string1):
return len(string1)
word_list = ['Python', 'is', 'better', 'than', 'C']
word_list.sort()
print(word_list)
# ['C', 'Python', 'better', 'is', 'than']
word_list = ['Python', 'is', 'better', 'than', 'C']
word_list.sort(key=compare_num_of_chars)
print(word_list)
# ['C', 'is', 'than', 'Python', 'better']
# sorted 函数
x = (4, 3, 1, 2)
y = sorted(x)
print(y)
# [1, 2, 3, 4]
z = sorted(x, reverse=True)
print(z)
# [4, 3, 2, 1]
# :[[1, 2, 3], [2, 1, 3], [4, 0, 1]] 得到 [[4, 0, 1], [2, 1, 3], [1, 2, 3]]
# lambda
def sort_by_second_element(list_of_lists):
"""
按每个子列表的第二个元素对列表进行排序。
参数:
list_of_lists (list): 包含子列表的列表。
返回值:
list: 排序后的列表。
"""
list_of_lists.sort(key=lambda sublist: sublist[1])
return list_of_lists
my_list = [[1, 2, 3], [2, 1, 3], [4, 0, 1]]
sorted_list = sort_by_second_element(my_list)
print(sorted_list)
# 输出: [[4, 0, 1], [2, 1, 3], [1, 2, 3]]
# 简单自定义方法
def sort_by_second(sublist):
return sublist[1]
my_list = [[1, 2, 3], [2, 1, 3], [4, 0, 1]]
my_list.sort(key=sort_by_second) # 直接修改 my_list
print(my_list)
# 输出: [[4, 0, 1], [2, 1, 3], [1, 2, 3]]
# reverse 倒序
my_list = [[1, 2, 3], [2, 1, 3], [4, 0, 1]]
my_list.reverse()
print(my_list)
# 输出: [[1, 2, 3], [2, 1, 3], [4, 0, 1]]
# sort 倒序
my_list = [[1, 2, 3], [2, 1, 3], [4, 0, 1]]
my_list.sort(reverse=True)
print(my_list)
# 输出: [[1, 2, 3], [2, 1, 3], [4, 0, 1]]
# sorted 倒序
my_list = [[1, 2, 3], [2, 1, 3], [4, 0, 1]]
my_list_sorted = sorted(my_list, reverse=True)
print(my_list_sorted)
# 输出: [[4, 0, 1], [2, 1, 3], [1, 2, 3]]
查看代码 list_other
py
# 成员运算符
print(3 in [1, 3, 4, 5])
# True
print(3 not in [1, 3, 4, 5])
# False
print(3 in ["one", "two", "three"])
# False
print(3 not in ["one", "two", "three"])
# True
# 列表推导式
z = [1, 2, 3] + [4, 5]
print(z)
# [1, 2, 3, 4, 5]
z = [1, 2, 3] * 3
print(z)
# [1, 2, 3, 1, 2, 3, 1, 2, 3]
z = [None] * 4
print(z)
# [None, None, None, None]
# min 最小值 max 最大值
print(min([3, 7, 0, -2, 11]))
# -2
# print(max([4, "Hello", [1, 2]]))
# Traceback (most recent call last):
# File "<pyshell#58>", line 1, in <module>
# max([4, "Hello",[1, 2]])
# TypeError: '>' not supported between instances of 'str' and 'int'
# index 值的索引 找不到会报错
x = [1, 3, "five", 7, -2]
print(x.index(7))
# 3
# print(x.index(5))
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# ValueError: 5 is not in list
# count 计数
x = [1, 2, 2, 3, 5, 2, 5]
print(x.count(2))
# 3
print(x.count(5))
# 2
print(x.count(4))
# 0
查看代码 deep_copy
py
# 浅拷贝
x = [[0],[1]]
y = x[:] # 切片 浅拷贝
print(y)
# [[0], [1]]
x[0][0] = 100
print(y)
# [[100], [1]]
import copy
x = [[0],[1]]
y = copy.deepcopy(x) # 浅拷贝
print(y)
# [[0], [1]]
x[0][0] = 100
print(y)
# [[0], [1]]
查看代码 tuple
py
x = ('a', 'b', 'c')
# 1、基本操作
# 元组创建完成后,就能像列表一样使用了。
print(x[2])
# 'c'
print(x[1:])
# ('b', 'c')
print(len(x))
# 3
print(max(x))
# 'c'
print(min(x))
# 'a'
print(5 in x)
# False
print(5 not in x)
# True
# 2、元组是不可变的,不能修改元素
# x[2] = 'd'
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'tuple' object does not support item assignment
# 3、元组操作符
print(x + x)
# ('a', 'b', 'c', 'a', 'b', 'c')
print(2 * x)
# ('a', 'b', 'c', 'a', 'b', 'c')
print(x[:])
# ('a', 'b', 'c')
print(x * 1)
# ('a', 'b', 'c')
print(x + ())
# ('a', 'b', 'c')
# 4、元组推导式
x = 3
y = 4
print((x + y)) # 此行代码将把x和y相加
# 7
print((x + y,)) # 跟了逗号就意味着,圆括号是用来标识元组的
# (7,)
print(()) # 用成对的空的圆括号创建一个空元组
# ()
# 5、元组 拆包、打包
(one, two, three, four) = (1, 2, 3, 4)
print("one",one)
one, two, three, four = 1, 2, 3, 4
print("one",one)
# 1
one, two = two, one
print("one",one)
# 2
print("two",two)
# 1
# 注意,带星号的元素会把多余的所有数据项接收为列表。
x = (1, 2, 3, 4)
a, b, *c = x
test = a, b, c
print("a, b, c",test)
# (1, 2, [3, 4])
a, *b, c = x
test = a, b, c
print("a, b, c",test)
# (1, [2, 3], 4)
*a, b, c = x
test = a, b, c
print("a, b, c",test)
# ([1, 2], 3, 4)
a, b, c, d, *e = x
test = a, b, c, d, *e
print("a, b, c, d, e",test)
# (1, 2, 3, 4, [])
# 当遇到列表分隔符时,也会执行打包和拆包操作:
[a, b] = [1, 2]
[c, d] = 3, 4
[e, f] = (5, 6)
(g, h) = 7, 8
i, j = [9, 10]
k, l = (11, 12)
print("a",a)
# 1
print("[b, c, d]",[b, c, d])
# [2, 3, 4]
print("(e, f, g)",(e, f, g))
# (5, 6, 7)
test = h, i, j, k, l
print("test",test)
# (8, 9, 10, 11, 12)
# 6、元组和列表的转换
print(list((1, 2, 3, 4)))
# [1, 2, 3, 4]
print(tuple([1, 2, 3, 4]))
# (1, 2, 3, 4)
print(list("Hello"))
# ['H', 'e', 'l', 'l', 'o']
print(tuple("Hello"))
# ('H', 'e', 'l', 'l', 'o')
# 测试题1 - 增删改元祖
# x = (1, 2, 3, 4)
# 以下操作都会报错
# x.append(1)
# x[1] = "hello"
# del x[2]
# 测试题2 - 元祖排序
x = (3, 1, 4, 2)
x.sort() # 不能直接排序
sorted_x = sorted(x) # 返回一个排好序的列表 [1, 2, 3, 4]
sorted_x_tuple = tuple(sorted_x)
print(sorted_x_tuple) # 输出 (1, 2, 3, 4)
查看代码 set
py
# 1、集合
x = set([1,2,3,1,3,5])
print(x)
# {1, 2, 3, 5}
x.add(6)
print(x)
# {1, 2, 3, 5, 6}
x.remove(5)
print(x)
# {1, 2, 3, 6}
test = 1 in x
print(test)
# True
test = 4 in x
print(test)
# False
v = set([1,7,8,9])
test = x | v # 并集
print(test)
# {1, 2, 3, 6, 7, 8, 9}
test = x & v # 交集
print(test)
# {1}
test = x - v # x有,v没有
print(test)
# {2, 3, 6}
test = x ^ v # 对称差(symmetric difference)。
# 对称差是指,属于其中一个但不同时属于两个集合的元素。
print(test)
# {2, 3, 6, 7, 8, 9}
# 2、不可变集合
x = set([1, 2, 3, 1, 3, 5])
z = frozenset(x)
print(z)
# frozenset({1, 2, 3, 5})
# z.add(6)
# Traceback (most recent call last):
# File "<pyshell#79>", line 1, in <module>
# z.add(6)
# AttributeError: 'frozenset' object has no attribute 'add'
x.add(z)
print(x)
# {1, 2, 3, 5, frozenset({1, 2, 3, 5})}
# 测试题1
test = set([1, 2, 5, 1, 0, 2, 3, 1, 1, (1, 2, 3)])
print(test)
# {0, 1, 2, 3, 5, (1, 2, 3)}
print(len(test))
# 6
# 测试题2
temperatures = []
with open('./src/lab_05.txt') as infile:
for row in infile:
# row.strip() 去除字符串首尾的空白字符
# float(row.strip()) 将字符串转换为浮点数
# int(...):将字符串转换为整数
temperatures.append(float(row.strip()))
print(temperatures)
min_temp = min(temperatures)
print("min_temp",min_temp)
max_temp = max(temperatures)
print("max_temp",max_temp)
len_temperatures = len(temperatures)
print("len_temperatures",len_temperatures)
# 平均温度和中位数温度
average_temp = sum(temperatures) / len_temperatures
print("average_temp",average_temp)
# 中位数温度
median_temp = sorted(temperatures)[len_temperatures // 2]
print("median_temp",median_temp)
# 列表中有多少个温度值是唯一的
# 第一种思路
# temperatures = [1,2,3,4,5,6,7,8,9,10,1]
unique_temperatures = len(temperatures) - (len(temperatures) - len(set(temperatures)) )* 2 # 原始公式
# unique_temperatures = len(temperatures) - (len(temperatures)*2 - len(set(temperatures)) * 2)
# unique_temperatures = len(temperatures) - len(temperatures)*2 + len(set(temperatures)) * 2
# unique_temperatures = - len(temperatures) + len(set(temperatures)) * 2
# unique_temperatures = len(set(temperatures)) * 2 - len(temperatures) # 最终简化公式
# print(len(set(temperatures)))
# print(len(temperatures))
unique_temperatures = len(set(temperatures)) * 2 - len(temperatures)
print("unique_temperatures",unique_temperatures)
# 当temtemperatures的重复的1不知道出现多了多少次时候,这种方法就行不通了
# temperatures = [1,2,3,4,5,6,7,8,9,10,1,1,1,1,1,1,1,1,1,1,1,1]
# 原始公式 (len(temperatures) - len(set(temperatures)) )* 2 是认为1出现了2次,现在1重复了多次,就不行了
# 另外一种思路就是:可以用总长度减所有重复元素的重复次数,再加上set的长度,就是唯一值的个数
# 第二种思路
# 遍历列表,用一个字典统计每个元素出现的次数。
# 再遍历统计字典,数出现次数为1的元素个数。
def count_unique_once(lst):
counts = {}
for item in lst:
if item in counts:
counts[item] += 1
else:
counts[item] = 1
# 实现1
# unique_once_count = 0
# for _key, val in counts.items():
# if val == 1:
# unique_once_count += 1
# return unique_once_count
# 实现2
# return sum(1 for val in counts.values() if val == 1)
# 实现3
return len(list(filter(lambda x: x == 1, counts.values())))
# 测试
lst = [1, 2, 2, 2,2,2,2,2,2,2,2,3, 4, 4, 5,10,89,4,4,4,4]
print(count_unique_once(lst)) # 输出 3,唯一值为 1,3,5
print(count_unique_once(temperatures)) # 输出 3,唯一值为 1,3,5
- 3
查看代码 string
py
# 1、索引、切片语法
x = "Hello"
print(x[0])
# 'H'
print(x[-1])
# 'o'
print(x[1:])
# 'ello'
x = "Goodbye\n"
x = x[:-1]
print(x)
# 'Goodbye'
print(len("Goodbye"))
# 7
# 2、拼接字符串
x = "Hello" + "World"
print(x)
# 'HelloWorld'
print(8 * "x")
# 'xxxxxxxx'
# 3、转义字符
# 3、1
print("m")
# 'm'
print("\155")
# 'm'
print("\x6D")
# 'm'
# 3、2
print("1", "\n")
# '\n'
print("2", "\012")
# '\n'
print("3", "\x0A")
# '\n'
# 3、3
# \N{名称} 来插入具有特定 Unicode 名称的字符
unicode_a = "\N{LATIN SMALL LETTER A}" # A
print(unicode_a)
# 'a' #1
unicode_a_with_acute = "\N{LATIN SMALL LETTER A WITH ACUTE}"
print(unicode_a_with_acute)
# 'á'
print("\u00E1") # B
# 'á'
# 3、4
"a\n\tb" # 交互式环境下
"a\n\tb"
print("a\n\tb")
# a
# b
print("abc\n")
# abc
#
print("abc\n", end="")
# abc
# 4、字符串方法
# 4、1、join、split
x = " ".join(["join", "puts", "spaces", "between", "elements"])
print(x)
# 'join puts spaces between elements'
x = "::".join(["Separated", "with", "colons"])
print(x)
# 'Separated::with::colons'
x = "".join(["Separated", "by", "nothing"])
print(x)
# 'Separatedbynothing'
# 在默认情况下,split方法将依据所有空白字符进行拆分,而不仅是一个空格符。
x = "You\t\t can have tabs\t\n \t and newlines \n\n mixed in"
y = x.split()
print(y)
# ['You', 'can', 'have', 'tabs', 'and', 'newlines', 'mixed', 'in']
x = "Mississippi"
y = x.split("ss")
print(y)
# ['Mi', 'i', 'ippi']
x = "a b c d"
y = x.split(None, 1)
print(y)
# ['a', 'b c d']
y = x.split(" ", 1)
print(y)
# ['a', 'b c d']
y = x.split(" ", 2)
print(y)
# ['a', 'b', 'c d']
x.split(" ", 9)
["a", "b", "c", "d"]
x = "this is a test"
y = "-".join(x.split())
print(y)
# 'this-is-a-test'
print(x.replace(" ", "-"))
# 'this-is-a-test'
# 4、2、字符串转换为数值
print(float("123.456"))
# 123.456
# print(float('xxyy'))
# ValueError: could not convert string to float: 'xxyy'
print(int("3333"))
# 3333
# print(int('123.456')) #A
# ValueError: invalid literal for int() with base 10: '123.456'
# File "<stdin>", line 1, in ?
# ValueError: invalid literal for int() with base 10: '123.456'
# int函数还可以接受第二个可选参数,用来指定转换输入的字符串时采用的数值进制
print(int("10000", 8)) # B
# 4096
print(int("101", 2))
# 5
print(int("ff", 16))
# 255
# print(int('123456', 6)) #C
# ValueError: invalid literal for int() with base 6: '123456'
# print(int('a1'))
# invalid literal for int() with base 10: 'a1'
# print(int('12G', 16))
# invalid literal for int() with base 16: '12G'
print(float("12345678901234567890"))
# 1.2345678901234568e+23
# print(int("12*2"))
# invalid literal for int() with base 10: '12*2'
# 4、3、去除多余空白符
x = " Hello, World\t\t "
print(x.strip())
# 'Hello, World'
print(x.lstrip())
# 'Hello, World\t\t '
print(x.rstrip())
# ' Hello, World'
import string
print(string.whitespace)
# print 打印不出来,再交互式环境下打印结果如下
# ' \t\n\r\x0b\x0c'
# print 打印不出来,再交互式环境下打印结果如下
print(" \t\n\r\v\f")
# ' \t\n\r\x0b\x0c'
x = "www.python.org"
print(x.strip("w")) # A
# '.python.org'
print(x.strip("gor")) # 删除头尾所有的g、o、r字符
# 'www.python.'
print(x.strip(".gorw")) # 删除头尾所有的.、g、o、r、w字符
# 'python'
x = "(name, date), \n"
print(x.rstrip("),"))
# (name, date), \n
print(x.strip("),\n"))
# (name, date),
print(x.strip("\n)(,"))
# name, date),
# 4、4、字符串搜索
x = "Mississippi"
print(x.find("ss"))
# 2
print(x.find("zz"))
# -1
print(x.find("ss", 3))
# 5
print(x.find("ss", 0, 3))
# -1
print(x.rfind("ss"))
# 5
print(x.count("ss"))
# 2
x = "Mississippi"
print(x.startswith("Miss"))
# True
print(x.startswith("Mist"))
# False
print(x.endswith("pi"))
# True
print(x.endswith("p"))
# False
print(x.endswith(("i", "u"))) # Mississippi 满足一个条件就返回True
# True
# 4、5、字符串修改
x = "Mississippi"
print(x.replace("ss", "+++"))
# 'Mi+++i+++ippi'
# 一次性把多个字符替换为对应字符
x = "~~~~~~x ^ (y % z)"
table = x.maketrans("~^()", "!&[]")
print(x.translate(table))
# '!!!!!!x & [y % z]'
x = "mississippI anDDDDDD"
print(x.capitalize()) # 首字母大写,同时会将其他字母转换为小写
# 'Mississippi anddddddd'
print(x.title()) # 每个单词首字母大写
# 'Mississippi Anddddddd'
print(x.swapcase()) # 大小写互换
# 'MISSISSIPPi ANDDDDDD'
print(x.upper()) # 全部转换为大写
# 'MISSISSIPPI ANDDDDDD'
print(x.lower()) # 全部转换为小写
# 'mississippi anddddddd'
x = "\t\n\t\t\t\t\t"
print(x.expandtabs(1)) # 将1个制表符转换为1个空格
# ' \n '
print(x.expandtabs(2)) # 将1个制表符转换为2个空格
# ' \n '
# 4、6、利用列表修改字符串
text = "Hello, World"
wordList = list(text)
wordList[6:] = [] # A
wordList.reverse()
text = "".join(wordList)
print(text) # B
# ,olleH
# 速测题:字符串的修改要把字符串中的所有标点符号替换为空格符,比较快捷的方案是什么?
import string
# 获取所有的标点字符串
print(string.punctuation)
def replace_punctuation_with_space(text):
"""将字符串中所有标点符号替换为空格"""
translator = str.maketrans(string.punctuation, " " * len(string.punctuation))
return text.translate(translator)
# 使用示例
sample_text = "Hello, world! This is a test-string."
cleaned_text = replace_punctuation_with_space(sample_text)
print(cleaned_text) # 输出: "Hello world This is a test string "
# 4、7、其他方法
x = "123"
print(x.isdigit()) # 是否包含数字
# True
x = "abc"
print(x.isalpha()) # 是否包含字母
# True
x = "M"
print(x.islower()) # 是否全为小写字母
# False
print(x.isupper()) # 是否全为大写字母
# True
print(string.whitespace) # 空格字符串
print(string.digits) # 数字字符串 0 1 2 3 4 5 6 7 8 9
print(string.hexdigits) # 十六进制字符串 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
print(string.octdigits) # 八进制字符串 0 1 2 3 4 5 6 7
print(string.ascii_lowercase) # 所有小写ASCII字母字符
print(string.ascii_uppercase) # 所有大写ASCII字母字符
print(string.ascii_letters) # 所有ASCII字母字符
# 速测题:将列表中的字符串中的双引号替换为空格
x = ['"abc"', "def", '"ghi"', '"klm"', "nop"]
print((",".join(x).replace('"', "").split(",")))
print(list(map(lambda y: y.replace('"', ""), x)))
# ['abc', 'def', 'ghi', 'klm', 'nop']
# 速测题2:如何查找"Mississippi"中最后一个字母p的位置?找到后又该如何只去除该字母呢?
x = "Mississippi"
index = x.rfind("p")
y = x[:index] + x[index + 1 :]
print(y)
# Mississipi
# 5、将对象转为字符串
print(repr([1, 2, 3]))
# '[1, 2, 3]'
x = [1]
x.append(2)
x.append([3, 4])
print("the list x is " + repr(x))
# the list x is [1, 2, [3, 4]]
print(repr(len))
# <built-in function len>
# 6、格式化字符串 format
# 6.1
x = "{0} is the {1} of {2}".format("Ambrosia", "food", "the gods") # 1
print(x)
# 'Ambrosia is the food of the gods'
x = "{{Ambrosia}} is the {0} of {1}".format("food", "the gods") # 2
print(x)
# '{Ambrosia} is the food of the gods'
# 6.2
x = "{food} is the food of {user}".format(food="Ambrosia", user="the gods")
print(x)
# 'Ambrosia is the food of the gods'
x = "{0} is the food of {user[1]}".format(
"Ambrosia", user=["men", "the gods", "others"]
)
print(x)
# 'Ambrosia is the food of the gods'
# 6.3
x = "{0:10} is the food of gods".format("Ambrosia") # 1
print(x)
# 'Ambrosia is the food of gods'
x = "{0:{1}} is the food of gods".format("Ambrosia", 10) # 2
print(x)
# 'Ambrosia is the food of gods'
x = "{food:{width}} is the food of gods".format(food="Ambrosia", width=10)
print(x)
# 'Ambrosia is the food of gods'
x = "{0:>10} is the food of gods".format("Ambrosia") # 3
print(x)
# ' Ambrosia is the food of gods'
x = "{0:&>10} is the food of gods".format("Ambrosia") # 4
print(x)
# '&&Ambrosia is the food of gods'
# 自测题
x = "{1:{0}}".format(3, 4)
print(x)
# ' 4'
x = "{0:$>5}".format(3)
print(x)
# '$$$$3'
x = "{a:{b}}".format(a=1, b=5)
print(x)
# ' 1'
x = "{a:{b}}:{0:$>5}".format(3, 4, a=1, b=5, c=10)
print(x)
# ' 1:$$$$3'
# 7、用%格式化字符串
x = "%s is the %s of %s" % ("Ambrosia", "food", "the gods")
print(x)
# 'Ambrosia is the food of the gods'
x = "%s is the %s of %s" % ("Nectar", "drink", "gods")
print(x)
# 'Nectar is the drink of gods'
x = "%s is the %s of the %s" % ("Brussels Sprouts", "food", "foolish")
print(x)
# 'Brussels Sprouts is the food of the foolish'
x = [1, 2, "three"]
x = "The %s contains: %s" % ("list", x)
print(x)
# 'The list contains: [1, 2, 'three']'
# 输出宽度(字符总数)设定为6,将小数点后面的字符数设定为2,并将数字左对齐。
x = "Pi is <%-6.2f>" % 3.14159 # use of the formatting sequence: %–6.2f
print(x)
# 'Pi is <3.14 >'
num_dict = {"e": 2.718, "pi": 3.14159}
print("%(pi).2f - %(pi).4f - %(e).2f" % num_dict)
# 3.14 - 3.1416 - 2.72
print("a", "b", "c", sep="|")
# a|b|c
print("a", "b", "c", end="\n\n")
# a b c
#
print("a", "b", "c", sep="|", end="\n\n")
# a|b|c
#
# print("a", "b", "c", file=open("testfile.txt", "w"))
# 速测题
x = "%.2f" % 1.1111
print(x)
# '1.11'
x = "%(a).2f" % {"a": 1.1111}
print(x)
# '1.11'
x = "%(a).08f" % {"a": 1.1111}
print(x)
# '1.11110000'
# 8 字符串内插
value = 42
message = f"The answer is {value}"
print(message)
# The answer is 42
pi = 3.1415
# 当同时指定了字段宽度和精度时,精度指的是 小数点前的位数和小数点后的位数之和,而不是单纯的小数点后的位数。
print(f"pi is {pi:{10}.{2}f}")
# pi is 3.14
print(f"pi is {pi:{10}.{2}}")
# pi is 3.1
print(f"pi is {pi:10.2f}")
# pi is 3.14
print(f"pi is {pi:10.2}")
# pi is 3.1
# 9 Bytes
unicode_a_with_acute = "\N{LATIN SMALL LETTER A WITH ACUTE}"
print(unicode_a_with_acute)
# 'á'
xb = unicode_a_with_acute.encode() # 1
print(xb)
# b'\xc3\xa1' #2
# xb += 'A' #3
# Traceback (most recent call last):
# File "<pyshell#35>", line 1, in <module>
# xb += 'A'
# TypeError: can't concat str to bytes
x = xb.decode() # 4
print(x)
# 'á'
print("你好".encode())
# b'\xe4\xbd\xa0\xe5\xa5\xbd'
# 研究题
with open("./src/moby_01.txt") as infile, open(
"./src/moby_01_clean.txt", "w"
) as outfile:
for line in infile:
# 全都转成大写或小写
line = line.upper()
# 删除标点符号
line = line.translate(
str.maketrans(string.punctuation, " " * len(string.punctuation))
)
# 拆分为单词
words = line.split()
# 将全部单词按一行写入
# cleaned_words = " ".join(words)
# outfile.write(cleaned_words)
# 将全部单词按每行一个写入
for word in words:
outfile.write(word + "\n")
- 4
查看代码 dict
py
# 字典
# 1、基本操作
x = []
y = {}
y[0] = "Hello"
y[1] = "Goodbye"
# x[0] = 'Hello' 如果初始化没有指定,则不能赋值
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# IndexError: list assignment index out of range
print(y[0])
# Hello
print(y[1] + ", Friend.")
# 'Goodbye, Friend.'
y["two"] = 2
y["pi"] = 3.14
print(y["two"] * y["pi"])
# 6.28
english_to_french = {} # A
english_to_french["red"] = "rouge" # B
english_to_french["blue"] = "bleu"
english_to_french["green"] = "vert"
print("red is", english_to_french["red"]) # C
# red is rouge
# 手动题
# dicts = {}
# for idx in range(1,4):
# name = input(f"请输入第{idx}个姓名: ")
# age = input(f"请输入第{idx}个年龄: ")
# dicts[name] = age
# find_name = input("请输入要查找的姓名: ")
# print(dicts[find_name])
# 2、其他操作
english_to_french = {"red": "rouge", "blue": "bleu", "green": "vert"}
print(len(english_to_french))
x = english_to_french.keys()
print(x)
# dict_keys(['red', 'blue', 'green'])
x = list(english_to_french.keys())
print(x)
# ['green', 'blue', 'red']
x = list(english_to_french.values())
print(x)
# ['vert', 'bleu', 'rouge']
x = list(english_to_french.items())
print(x)
# [('green', 'vert'), ('blue', 'bleu'), ('red', 'rouge')]
del english_to_french["green"]
x = list(english_to_french.items())
print(x)
# [('blue', 'bleu'), ('red', 'rouge')]
print("red" in english_to_french)
# True
print("orange" in english_to_french)
# False
print(english_to_french.get("blue", "No translation"))
# bleu
print(english_to_french.get("chartreuse", "No translation2"))
# No translation
print(english_to_french.get("chartreuse"))
# None
print(english_to_french.setdefault("chartreuse", "No translation"))
# No translation
print(english_to_french.setdefault("blue", "No translation"))
# bleu
x = {0: "zero", 1: "one"}
y = x.copy()
print(y)
# {0: 'zero', 1: 'one'}
z = {1: "One", 2: "Two"}
x = {0: "zero", 1: "one"}
x.update(z)
print(x)
# {0: 'zero', 1: 'One', 2: 'Two'}
# 速测题
x = {"a": 1, "b": 2, "c": 3, "d": 4}
y = {"a": 6, "e": 5, "f": 6}
del x["d"]
print(x)
# {'a': 1, 'b': 2, 'c': 3}
z = x.setdefault("g", 7)
print(x)
# {'a': 1, 'b': 2, 'c': 3, 'g': 7}
print(z)
# 7
x.update(y)
print(x)
# {'a': 6, 'b': 2, 'c': 3, 'g': 7,'e': 5, 'f': 6, }
print(x.keys())
# dict_keys(['a', 'b', 'c', 'g', 'e', 'f'])
# 3、单词计数
sample_string = "To be or not to be"
occurrences = {}
for word in sample_string.split():
occurrences[word] = occurrences.get(word, 0) + 1 # 1
for word in occurrences:
print("The word", word, "occurs", occurrences[word], "times in the string")
# The word To occurs 1 times in the string
# The word be occurs 2 times in the string
# The word or occurs 1 times in the string
# The word not occurs 1 times in the string
# The word to occurs 1 times in the string
print("--------------------------------")
from collections import Counter
sample_string = "To be or not to be"
occurrences = Counter(sample_string.split())
print(occurrences)
for word in occurrences:
print("The word", word, "occurs", occurrences[word], "times in the string")
# 4、稀疏矩阵
# matrix = [[3, 0, -2, 11], [0, 9, 0, 0], [0, 7, 0, 0], [0, 0, 0, -5]]
matrix = {(0, 0): 3, (0, 2): -2, (0, 3): 11, (1, 1): 9, (2, 1): 7, (3, 3): -5}
for rownum, colnum in matrix:
print(rownum, colnum)
print(matrix[(rownum, colnum)])
print(matrix.get((rownum, colnum), 0))
element = matrix[(rownum, colnum)]
# element = matrix.get((rownum, colnum),0)
else:
element = 0
# 5、字典作为缓存
# def sole(m, n, t):
# # . . . do some time-consuming calculations . . .
# return(result)
import random
sole_cache = {}
def sole(m, n, t):
if (m, n, t) in sole_cache:
print("缓存中...")
return sole_cache[(m, n, t)]
else:
print("计算中...")
# . . . do some time-consuming calculations . . .
result = random.randint(1, 100)
sole_cache[(m, n, t)] = result
return result
print(sole(1, 2, 3))
print(sole(1, 2, 3))
# 研究题:用字典来统计每个单词出现的次数,然后将最常用和最不常用的单词打印出来。
word_count = {}
with open("./src/moby_01_clean.txt") as infile:
word_count = Counter(map(lambda x: x.strip(), infile))
# 最常用
print(word_count.most_common(5))
# 最不常用:方法1
print(word_count.most_common()[:-6:-1])
# 最不常用:方法2
word_count_list = list(word_count.items())
word_count_list.sort(key=lambda sublist: sublist[1])
print(word_count_list[:5])
- 5
查看代码 loop
py
# 流程控制
# 1、if elseif else
x = 10
if x < 5:
pass
print("x < 5")
else:
x = 5
print(x)
# 2、for 循环
x = [1.0, 2.0, 3.0]
for n in x:
print(1 / n)
# 2-1、range函数
x = [1, 3, -7, 4, 9, -5, 4]
for i in range(len(x)):
if x[i] < 0:
print("Found a negative number at index ", i)
print(range(3, 7))
x = list(range(3, 7)) # 1
print(x)
# [3, 4, 5, 6]
x = list(range(2, 10)) # 1
print(x)
# [2, 3, 4, 5, 6, 7, 8, 9]
x = list(range(5, 3))
print(x)
# []
x = list(range(0, 10, 2))
print(x)
# [0, 2, 4, 6, 8]
x = list(range(5, 0, -1))
print(x)
# [5, 4, 3, 2, 1]
# 2-2、元组拆包
somelist = [(1, 2), (3, 7), (9, 5)]
result = 0
for t in somelist:
result = result + (t[0] * t[1])
print(result)
somelist = [(1, 2), (3, 7), (9, 5)]
result = 0
for x, y in somelist:
result = result + (x * y)
print(result)
# 2-3、enumerate
x = [1, 3, -7, 4, 9, -5, 4]
for i, n in enumerate(x): # 1
if n < 0: # 2
print("Found a negative number at index ", i) # 3
# 2-4、zip
x = [1, 2, 3, 4]
y = ["a", "b", "c"] # 最短的列表长度决定结果长度
z = zip(x, y)
print(list(z))
# [(1, 'a'), (2, 'b'), (3, 'c')] #B
# 动手题
x = [1, 3, 5, 0, -1, 3, -2]
y = filter(lambda x: x > 0, x)
print(y)
# <filter object at 0x000001D57B2FBEE0>
print(list(y))
# [1, 3, 5, 3]
print(tuple(y))
# ()
# 3、列表推导式、字典推导式、生成器表达式
x = [1, 2, 3, 4]
x_squared = []
for item in x:
x_squared.append(item * item)
print(x_squared)
# [1, 4, 9, 16]
x = [1, 2, 3, 4]
x_squared = [item * item for item in x]
print(x_squared)
# [1, 4, 9, 16]
x = [1, 2, 3, 4]
x_squared = [item * item for item in x if item > 2]
print(x_squared)
# [9, 16]
x = [1, 2, 3, 4]
x_squared_dict = {item: item * item for item in x}
print(x_squared_dict)
# {1: 1, 2: 4, 3: 9, 4: 16}
x = [1, 2, 3, 4]
x_squared = (item * item for item in x)
print(x_squared)
# <generator object <genexpr> at 0x102176708>
for square in x_squared:
print(square)
# 1 4 9 16
# 动手题
x = [1, 2, 3, 4, -1, 3, -2]
y = [item for item in x if item > 0]
print(y)
# [1, 2, 3, 4, 3]
x = range(1, 100)
y = (item for item in x if (item % 2) != 0)
print(y)
# <generator object <genexpr> at 0x000002986A8F2B50>
print(list(y))
# [1, 3, 5, 7, 9, ..., 99]
x = range(11, 15)
y = [item * item * item for item in x]
print(y)
# [1331, 1728, 2197, 2744]
# 4、语句、块和缩进
x = 1
y = 0
z = 0
if x > 0:
y = 1
z = 10
else:
y = -1
print(x, y, z)
# 1 1 10
# x = 1
# File "<stdin>", line 1
# x = 1
# ^
# IndentationError: unexpected indent
v = 1
x = 1
z = 0
y = 0
if x == 1:
y = 2
if v > 0:
z = 2
v = 0
x = 1
if x == 1:
y = 2
# z = 2
# File "<stdin>", line 3
# z = 2
# ^
# IndentationError: unindent does not match any outer indentation level
print("string1", "string2", "string3", "string4", "string5")
# string1 string2 string3 string4 string5
x = 100 + 200 + 300 + 400 + 500
print(x)
# 1500
v = [100, 300, 500, 700, 900, 1100, 1300]
print(v)
# [100, 300, 500, 700, 900, 1100, 1300]
print(max(1000, 300, 500, 800, 1200))
# 1200
x = 100 + 200 + 300 + 400 + 500
print(x)
# 1500
x = "strings separated by whitespace " """are automatically""" " concatenated"
print(x)
# 'strings separated by whitespace are automatically concatenated'
x = 1
if x > 0:
string1 = "this string broken by a backslash will end up \
with the indentation tabs in it"
print(string1)
# this string broken by a backslash will end up with the indentation tabs in it
if x > 0:
string1 = "this can be easily avoided by splitting the " "string in this way"
print(string1)
# 'this can be easily avoided by splitting the string in this way'
# 6、布尔值
# 看为true或者false的最终的落脚点
x = [2] and [3, 4]
print(x)
# [3, 4]
x = [] and 5
print(x)
# []
x = [] and 0
print(x)
# []
x = 5 and []
print(x)
# []
x = [2] or [3, 4]
print(x)
# [2]
x = [] or 5
print(x)
# 5
x = 5 or []
print(x)
# 5
x = [] or 0
print(x)
# 0
x = [0]
y = [x, 1]
print(x is y[0])
# True
x = [0]
print(x is y[0])
# False
print(x == y[0])
# True
if 1 > 0 and []: # false
print(1)
- 6
查看代码 def
py
# def
# 1、函数
def fact(n):
"""Return the factorial of the given number.""" #1
r = 1
while n > 0:
r = r * n
n = n - 1
return r #2
x = fact(4) #3
print(x)
# 24
# 2、参数
# 2.1 形参
def power(x, y):
r = 1
while y > 0:
r = r * x
y = y - 1
return r
x = power(3, 3)
print(x)
# 27
# power(3)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: power() missing 1 required positional argument: 'y'
# 2.2 默认值
def power(x, y=2):
r = 1
while y > 0:
r = r * x
y = y - 1
return r
x = power(3, 3)
print(x)
# 27
x = power(3)
print(x)
# 9
x = power(2, 3)
print(x)
# 8
x = power(3, 2)
print(x)
# 9
x = power(y=2, x=3)
print(x)
# 9
def list_file_info(size=False, create_date=False, mod_date=False ):
# get file names
if size:
# code to get file sizes goes here
pass
if create_date:
# code to get create dates goes here
pass
# do any other stuff desired
fileinfostructure = 123
return fileinfostructure
fileinfo = list_file_info(size=True, mod_date=True)
print(fileinfo)
# 2.3 参数量不定时的处理 (* 返回的是元组)
def maximum(*numbers):
# 寻找最大值
print(numbers) # 是一个元组
if len(numbers) == 0:
return None
else:
maxnum = numbers[0]
for n in numbers[1:]:
if n > maxnum:
maxnum = n
return maxnum
x = maximum(3, 2, 8)
print(x)
# 8
x = maximum(1, 5, 9, -2, 2)
print(x)
# 9
# 2.4 参数量不定时的处理 (** 返回的是字典)
def example_fun(x, y, **other):
print("x: {0}, y: {1}, keys in 'other': {2}".format(x,
y, list(other.keys())))
other_total = 0
for k in other.keys():
other_total = other_total + other[k]
print("The total of values in 'other' is {0}".format(other_total))
example_fun(2, y="1", foo=3, bar=4)
# x: 2, y: 1, keys in 'other': ['foo', 'bar']
# The total of values in 'other' is 7
# 速测题目
def reversedPrint (*numbers):
print(*reversed(numbers))
# print(*[1,2,3,4])
reversedPrint(1,2,3,410,9,89)
# 3、将可变对象用作函数实参
def f(n, list1, list2):
list1.append(3)
list2 = [4, 5, 6]
n = n + 1
x = 5
y = [1, 2] # 只有y收到了影响
z = [4, 5]
f(x, y, z)
print(x, y, z)
# (5, [1, 2, 3], [4, 5])
# 4、全局变量
# 局部变量
def fact(n):
"""Return the factorial of the given number."""
r = 1
while n > 0:
r = r * n
n = n - 1
return r
def fun():
global a
a = 1
print("fun b",b) # 闭包
# b = 2
a = "one"
b = "two"
fun()
print(a)
# 1
print(b)
# 'two'
g_var = 0
nl_var = 0 #innertest函数中的gvar绑定为同名的顶级变量
print("top level-> g_var:{0} nl_var:{1}".format(g_var, nl_var))
def test():
nl_var = 2 # inner_test函数中的nlvar绑定为test函数中的同名变量
print("in test->g_var:{0} nl_var:{1}".format(g_var,nl_var))
def innertest():
global g_var # innertest函数中的g_var绑定为同名的顶级变量
nonlocal nl_var #inner_test函数中的nlvar绑定为test函数中的同名变量
print("in inner test-> g var: {0} nl var: {1}".format(g_var,nl_var))
g_var = 1
nl_var =4
print("in inner test-> g var: {0} nl var: {1}".format(g_var,nl_var))
innertest()
print("in test->g_var:{0} nl_var:{1}".format(g_var,nl_var))
test()
print("toplevel-> gvar: {0} nl_var: {1}".format(g_var,nl_var))
# top level-> g_var: 0 nl_var: 0
# in test-> g_var: 0 nl_var: 2
# in inner test-> g var: 0 nl var: 2
# in inner_test-> g_var: 1 nl_var: 4
# in test-> g_var: 1 nl_var: 4
# top level-> g_var: 1 nl_var: 0
# 动手题
x = 5
def funct_1():
x = 3
def funct_2():
global x
x = 2
funct_1()
print(x)
funct_2()
print(x)
# 5 将函数赋给变量
def f_to_kelvin(degrees_f): #A
return 273.15 + (degrees_f - 32) * 5 / 9
def c_to_kelvin(degrees_c): #B
return 273.15 + degrees_c
abs_temperature = f_to_kelvin #C
x = abs_temperature(32)
print(x)
# 273.15
abs_temperature = c_to_kelvin #D
x= abs_temperature(0)
print(x)
# 273.15
t = {'FtoK': f_to_kelvin, 'CtoK': c_to_kelvin} #1
x = t['FtoK'](32) #A
print(x)
# 273.15
x = t['CtoK'](0) #B
print(x)
# 273.15
# 6 lambda
t2 = {
'FtoK': lambda deg_f: 273.15 + (deg_f - 32) * 5 / 9, #1
'CtoK': lambda deg_c: 273.15 + deg_c
} #1
x = t2['FtoK'](32)
print(x)
# 273.15
# 7 Generator
def four():
x = 0 #A
while x < 4:
print("in generator, x =", x)
yield x #B
x += 1 #C
for i in four():
print(i)
# in generator, x = 0
# 0
# in generator, x = 1
# 1
# in generator, x = 2
# 2
# in generator, x = 3
# 3
def subgen(x):
for i in range(x):
yield i
def gen(y):
yield from subgen(y)
for q in gen(6):
print(q)
# 0
# 1
# 2
# 3
# 4
# 5
print(2 in four())
# in generator, x = 0
# in generator, x = 1
# in generator, x = 2
# True
print(5 in four())
# in generator, x = 0
# in generator, x = 1
# in generator, x = 2
# in generator, x = 3
# False
# 速测题
def range_x(max):
for e in range(max + 1):
yield e
print(1 in range_x(5))
print(5 in range_x(5))
print(6 in range_x(5))
print(6 in range_x(10))
# 8、 Decorators
def decorate(func):
print("in decorate function, decorating", func.__name__)
def wrapper_func(*args):
print("Executing", func.__name__)
return func(*args)
return wrapper_func
def myfunction(parameter):
print(parameter)
myfunction = decorate(myfunction)
# in decorate function, decorating myfunction
myfunction("hello")
# Executing myfunction
# hello
def decorate(func):
print("in decorate function, decorating", func.__name__) #1
def wrapper_func(*args):
print("Executing", func.__name__)
# 动手题
args = map(lambda x: "<html>" + x + "</html>", args)
return func(*args)
return wrapper_func #2
@decorate #3
def myfunction(parameter):
print(parameter)
# in decorate function, decorating myfunction #4
myfunction("hello")
# Executing myfunction
# hello
- 7
查看代码 module
py
# 模块 module
# pi
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# NameError: name 'pi' is not defined
# area(2)
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# NameError: name 'area' is not defined
import mymath
# pi
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# NameError: name 'pi' is not defined
print(mymath.pi)
# 3.14159
print(mymath.area(2))
# 12.56636
print(mymath.__doc__)
# 'mymath - our example math module'
print(mymath.area.__doc__)
# 'area(r): return the area of a circle with radius r.'
from mymath import pi
print(pi)
# 3.14159
# print(area(2))
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# NameError: name 'area' is not defined
import mymath, importlib
x = importlib.reload(mymath)
print(x)
# <module 'mymath' from '/home/doc/quickpythonbook/code/mymath.py'>
import sys
print(sys.path)
# _list of directories in the search path_
# 5 私有
from modtest import *
print(f(3))
# 3
# print(_g(3))
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# NameError: name '_g' is not defined
print(a)
# 4
# print(_b)
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# NameError: name '_b' is not defined
import modtest
print(modtest._b)
# 2
from modtest import _g
print(_g(5))
# 5
# 2 命名空间
print(locals())
# {'__builtins__': <module 'builtins' (built-in)>,
# '__name__': '__main__',
# '__doc__': None,
# '__package__': None}
print(globals())
# {'__builtins__': <module 'builtins' (built-in)>,
# '__name__': '__main__',
# '__doc__': None,
# '__package__': None}
z = 2
import math
from cmath import cos
print(globals())
# {'cos': <built-in function cos>, '__builtins__': <module 'builtins'
# (built-in)>, '__package__': None, '__name__': '__main__', 'z': 2,
# '__doc__': None, 'math': <module 'math' from
# '/usr/local/lib/python3.0/libdynload/math.so'>}
locals()
# {'cos': <built-in function cos>, '__builtins__':
# <module 'builtins' (built-in)>, '__package__': None, '__name__':
# '__main__', 'z': 2, '__doc__': None, 'math': <module 'math' from
# '/usr/local/lib/python3.0/libdynload/math.so'>}
print(math.ceil(3.4))
# 4
del z, math, cos
print(locals())
# {'__builtins__': <module 'builtins' (built-in)>, '__package__': None,
# '__name__': '__main__', '__doc__': None}
# math.ceil(3.4)
# Traceback (innermost last):
# File "<stdin>", line 1, in <module>
# NameError: math is not defined
import math
print(math.ceil(3.4))
# 4
print("--------------------------------")
def f(x):
print(globals())
print("Entry local: ", locals())
y = x
print("Exit local: ", locals())
z = 2
print(globals())
# {'f': <function f at 0xb7cbfeac>, '__builtins__': <module 'builtins'
# (built-in)>, '__package__': None, '__name__': '__main__', 'z': 2,
# '__doc__': None}
f(z)
# global: {'f': <function f at 0xb7cbfeac>, '__builtins__': <module
# 'builtins' (built-in)>, '__package__': None, '__name__': '__main__',
# 'z': 2, '__doc__': None}
# Entry local: {'x': 2}
# Exit local: {'y': 2, 'x': 2}
import scopetest
z = 2
scopetest.f(z)
# global: ['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__file__', '__cached__', '__builtins__', 'v', 'f']
# entry local: {'x': 2}
# exit local: dict_keys(['x', 'w', 'y'])
print(max.__doc__)
# max(iterable[, key=func]) -> value
# max(a, b, c, [, key=func]) -> value
# With a single iterable argument, return its largest item.
# With two or more arguments, return the largest argument.
print(list("Peyto Lake"))
# ['P', 'e', 'y', 't', 'o', ' ', 'L', 'a', 'k', 'e']
list = [1, 3, 5, 7]
# print(list("Peyto Lake"))
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# TypeError: 'list' object is not callable
import mymath
mymath = mymath.area
# mymath.pi
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: 'function' object has no attribute 'pi'
del list
print(list("Peyto Lake"))
# ['P', 'e', 'y', 't', 'o', ' ', 'L', 'a', 'k', 'e']
import mymath
print(mymath.pi)
3.14159
x1 = 6
xl = x1 - 2
print(x1)
# 6
print(dir()) # 返回当前命名空间中定义的对象名称列表
# ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x1', 'xl']
- 8
查看代码 program
py
def main(): #A
print("this is our first test script file")
main()
py
# python opts.py -x100 -q -f outfile 2 arg2
from argparse import ArgumentParser
def main():
parser = ArgumentParser()
parser.add_argument("indent", type=int, help="indent for report")
parser.add_argument("input_file", help="read data from this file") #1
# 两个位置参数indent和input_file,这是在全部可选参数都解析完毕后输入的参数。
# 位置参数是指那些没有前缀字符(通常是“-”)且必须给定的参数。
parser.add_argument("-f", "--file", dest="filename", #2
help="write report to FILE", metavar="FILE")
parser.add_argument("-x", "--xray",
help="specify xray strength factor")
parser.add_argument("-q", "--quiet",
action="store_false", dest="verbose", default=True, #3
help="don't print status messages to stdout")
args = parser.parse_args()
print("arguments:", args)
main()
# arguments: Namespace(filename='outfile', indent=2, input_file='arg2',verbose=False, xray='100')
py
# python script2.py arg1 arg2 3
import sys
def main():
print("this is our second test script file")
print(sys.argv)
main()
# this is our second test script file
# ['script2.py', 'arg1', 'arg2', '3']
py
# python replace.py zero 0 # 手动标准输入 ctrl+z 回车结束
# python replace.py zero 0 < infile > outfile # 文件中读取
# python replace.py a A < infile >> outfile # 追加
# python replace.py 0 zero < infile | python replace.py 1 one > outfile #管道
import sys
def main():
contents = sys.stdin.read() #A
# print(contents) # 这里打印内容会一起输出到outfile
sys.stdout.write(contents.replace(sys.argv[1], sys.argv[2])) #B
main()
py
# python script4.py sole1.tst sole2.tst
import fileinput
def main():
for line in fileinput.input():
if not line.startswith('##'):
print(line, end="")
main()
# 0 0 0
# 0100 0
# 0100100
# 12 15 0
# 100100 0
py
# python script5.py file1 file2
import fileinput
def main():
for line in fileinput.input():
if fileinput.isfirstline():
print("<start of file {0}>".format(fileinput.filename()))
print(line, end="")
main()
# <start of file file1>
# ...... . . ..
# .......................
# <start of file file2>
# ....... . . ..
# .......................
py
#! /usr/bin/env python3
import sys
# conversion mappings
_1to9dict = {
"0": "",
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
"8": "eight",
"9": "nine",
}
_10to19dict = {
"0": "ten",
"1": "eleven",
"2": "twelve",
"3": "thirteen",
"4": "fourteen",
"5": "fifteen",
"6": "sixteen",
"7": "seventeen",
"8": "eighteen",
"9": "nineteen",
}
_20to90dict = {
"2": "twenty",
"3": "thirty",
"4": "forty",
"5": "fifty",
"6": "sixty",
"7": "seventy",
"8": "eighty",
"9": "ninety",
}
def num2words(num_string):
if num_string == "0":
return "zero"
if len(num_string) > 2:
return "Sorry can only handle 1 or 2 digit numbers"
num_string = "0" + num_string
# A
tens, ones = num_string[-2], num_string[-1]
if tens == "0":
return _1to9dict[ones]
elif tens == "1":
return _10to19dict[ones]
else:
return _20to90dict[tens] + " " + _1to9dict[ones]
def main():
# 1
print(num2words(sys.argv[1]))
main()
py
#! /usr/bin/env python3
"""n2w: number to words conversion module: contains function
num2words. Can also be run as a script
usage as a script: n2w num
(Convert a number to its English word description)
num: whole integer from 0 and 999,999,999,999,999 (commas are
optional)
example: n2w 10,003,103
for 10,003,103 say: ten million three thousand one hundred three
"""
import sys, string, argparse
_1to9dict = {
"0": "",
"1": "one",
"2": "two",
"3": "three",
"4": "four", # B
"5": "five",
"6": "six",
"7": "seven",
"8": "eight",
"9": "nine",
}
_10to19dict = {
"0": "ten",
"1": "eleven",
"2": "twelve",
"3": "thirteen",
"4": "fourteen",
"5": "fifteen",
"6": "sixteen",
"7": "seventeen",
"8": "eighteen",
"9": "nineteen",
}
_20to90dict = {
"2": "twenty",
"3": "thirty",
"4": "forty",
"5": "fifty",
"6": "sixty",
"7": "seventy",
"8": "eighty",
"9": "ninety",
}
_magnitude_list = [
(0, ""),
(3, " thousand "),
(6, " million "),
(9, " billion "),
(12, " trillion "),
(15, ""),
]
def num2words(num_string):
"""num2words(num_string): convert number to English words"""
if num_string == "0": # C
return "zero"
num_string = num_string.replace(",", "")
num_length = len(num_string)
max_digits = _magnitude_list[-1][0]
if num_length > max_digits:
return "Sorry, can't handle numbers with more than " "{0} digits".format(
max_digits
)
num_string = "00" + num_string # D #F
word_string = ""
# E #F
for mag, name in _magnitude_list: # F
if mag >= num_length: # F
return word_string # F
else: # F
hundreds, tens, ones = (
num_string[-mag - 3],
num_string[-mag - 2],
num_string[-mag - 1],
) # F
if not (hundreds == tens == ones == "0"): # F
word_string = (
_handle1to999(hundreds, tens, ones) + name + word_string
) # F
def _handle1to999(hundreds, tens, ones):
if hundreds == "0":
return _handle1to99(tens, ones)
else:
return _1to9dict[hundreds] + " hundred " + _handle1to99(tens, ones)
def _handle1to99(tens, ones):
if tens == "0":
return _1to9dict[ones]
elif tens == "1":
return _10to19dict[ones]
else:
return _20to90dict[tens] + " " + _1to9dict[ones]
def test(): # G
values = sys.stdin.read().split()
for val in values:
print("{0} = {1}".format(val, num2words(val)))
def main():
parser = argparse.ArgumentParser(usage=__doc__)
parser.add_argument("num", nargs="*")
parser.add_argument(
"-t",
"--test",
dest="test",
action="store_true",
default=False,
help="Test mode: reads from stdin",
)
args = parser.parse_args()
if args.test: # H
test()
else:
try:
result = num2words(args.num[0])
except KeyError: # J
parser.error("argument contains non-digits")
else:
print("For {0}, say: {1}".format(args.num[0], result))
if __name__ == "__main__":
main() # 1
else:
print("n2w loaded as a module")
- 9
查看代码 file_os
py
# 文件系统的使用
# 1、路径
# 1.1、os
import os
# 获取当前工作目录
x = os.getcwd()
print(x)
x = os.listdir(os.getcwd())
print(x)
# 表示当前目录的字符串
x = os.curdir # 相对路径
print(x)
x = os.listdir()
print(x)
x = os.listdir(os.curdir)
print(x)
# 修改当前工作目录
# os.chdir("./src") # A
# x = os.getcwd()
# print(x)
# x = os.listdir(os.getcwd())
# print(x)
# 不同操作系统,返回的路径格式不同
x = os.path.join("bin", "utils", "disktools")
print(x)
# bin /utils/disktools
x = os.path.join("mydir\\bin", "utils\\disktools\\chkdisk")
print(x)
# mydir\bin\utils\disktools\chkdisk
path1 = os.path.join("mydir", "bin")
path2 = os.path.join("utils", "disktools", "chkdisk")
print(os.path.join(path1, path2))
# mydir\bin\utils\disktools\chkdisk
print(os.path.split(os.path.join("some", "directory", "path")))
# ('some\\directory', 'path')
x = os.path.basename(os.path.join("some", "directory", "path.jpg"))
print(x)
# 'path.jpg'
x = os.path.dirname(os.path.join("some", "directory", "path.jpg"))
print(x)
# 'some\\directory'
x = os.path.splitext(os.path.join("some", "directory", "path.jpg"))
print(x)
# ("some/directory/path", ".jpg")
x = os.path.splitext(os.path.join("some", "directory", "path"))
print(x)
# ("some/directory/path", "")
x = os.path.commonprefix(("\\aaa\\bbb", "\\aaa\\ccc"))
print(x)
# \\aaa
x = os.path.expanduser("~")
print(x)
# C:\Users\administrator
x = os.path.expandvars("$HOME\\temp")
print(x)
# C:\Users\administrator\temp
print("--------------------------------")
# 1.2、pathlib
import pathlib
cur_path = pathlib.Path()
x = cur_path.cwd()
print(x)
from pathlib import Path
cur_path = Path()
x = cur_path.joinpath("bin", "utils", "disktools")
print(x)
# bin\utils\disktools
x = cur_path / "bin" / "utils" / "disktools"
print(x)
# WindowsPath('bin/utils/disktools')
print(x.parts)
# ('bin', 'utils', 'disktools')
a_path = Path("some", "directory", "path.jpg")
print(a_path.name)
# "path.jpg"
print(a_path.parent)
# some\directory
print(a_path.suffix)
# ".jpg"
# 是否为绝对路径
x = os.path.isabs(os.path.join(os.pardir, "path"))
print(x)
# False
x = os.name
print(x)
# nt
if os.name == "posix":
root_dir = "/"
elif os.name == "nt":
root_dir = "C:\\"
else:
print("Don't understand this operating system!")
import sys
x = sys.platform
print(x)
# win32
# 获取环境变量
# x = os.environ
# print(x)
# 测试题:
# 如何利用os模块中的函数获取test.log文件的路径?
# 并在同一目录下为名为test.log.old的文件新建一个文件路径?
# 如何用pathlib模块完成同样的任务?
# 假设 test.log 文件名(可以是相对路径或绝对路径)
test_log = "test.log"
# 获取 test.log 文件的绝对路径
test_log_abs_path = os.path.abspath(test_log)
print(test_log_abs_path)
# 获取 test.log 所在目录
test_log_dir = os.path.dirname(test_log_abs_path)
# 在同一目录下创建 test.log.old 的路径
test_log_old_path = os.path.join(test_log_dir, "test.log.old")
print("test.log 绝对路径:", test_log_abs_path)
print("test.log.old 路径:", test_log_old_path)
# 假设 test.log 文件
test_log = Path("test.log")
# 获取 test.log 文件的绝对路径
test_log_abs_path = test_log.resolve()
print(test_log_abs_path)
# 获取文件所在目录
test_log_dir = test_log_abs_path.parent
# 在同一目录下创建 test.log.old 路径
test_log_old_path = test_log_dir / "test.log.old"
print("test.log 绝对路径:", test_log_abs_path)
print("test.log.old 路径:", test_log_old_path)
x = Path(os.pardir)
print(x)
# ".."
# 2、文件信息
x = os.path.exists("C:\\Users\\myuser\\My Documents")
print(x)
# False
x = os.path.exists("C:\\Users\\myuser\\My Documents\\Letter.doc")
print(x)
# False
x = os.path.isdir("C:\\Users\\myuser\\My Documents")
print(x)
# True
x = os.path.isfile("C:\\Users\\ myuser\\My Documents")
print(x)
# False
x = os.path.isdir("C:\\Users\\ myuser\\My Documents\\Letter.doc")
print(x)
# False
x = os.path.isfile("C:\\Users\\ myuser\\My Documents\\Letter.doc")
print(x)
# True
print("--------------------------------")
with os.scandir(".") as my_dir:
for entry in my_dir:
print(entry.name, entry.is_file())
# pip-selfcheck.json True
# pyvenv.cfg True
# include False
# test.py True
# lib False
# lib64 False
# bin False
# os.scandir不会自动递归到各级子目录
# 如果需要递归子目录,可使用os.walk方法,如:
import os
from os.path import join, getsize
for root, dirs, files in os.walk("."):
print(root, "consumes")
# 计算当前目录 root 下所有 非目录文件 的大小总和:
# join(root, name) 拼接出文件完整路径
# getsize(...) 计算单个文件大小,单位是字节
# 最外层 sum(...) 把所有文件大小相加
print(
sum(getsize(join(root, name)) for name in files),
)
print("bytes in", len(files), "non-directory files")
# 即跳过 "CVS" 目录及其内容。
if "CVS" in dirs:
dirs.remove("CVS") # don't visit CVS directories
# 3、更多操作
# os.chdir(os.path.join("C:", "my documents", "tmp"))
# x = os.listdir(os.curdir)
# print(x)
# ["book1.doc.tmp", "a.tmp", "1.tmp", "7.tmp", "9.tmp", "registry.bkp"]
import glob
x = glob.glob("*")
print(x)
# ["book1.doc.tmp", "a.tmp", "1.tmp", "7.tmp", "9.tmp", "registry.bkp"]
x = glob.glob("*bkp")
print(x)
# ["registry.bkp"]
x = glob.glob("?.tmp")
print(x)
# ["a.tmp", "1.tmp", "7.tmp", "9.tmp"]
x = glob.glob("[0-9].tmp")
print(x)
# ["1.tmp", "7.tmp", "9.tmp"]
# os.rename("registry.bkp", "registry.bkp.old")
# x = os.listdir(os.curdir)
# print(x)
# ['book1.doc.tmp', 'a.tmp', '1.tmp', '7.tmp', '9.tmp', 'registry.bkp.old']
# os.remove("book1.doc.tmp")
# x = os.listdir(os.curdir)
# print(x)
# ['a.tmp', '1.tmp', '7.tmp', '9.tmp', 'registry.bkp.old']
# os.makedirs("mydir")
# x = os.listdir(os.curdir)
# print(x)
# ['mydir', 'a.tmp', '1.tmp', '7.tmp', '9.tmp', 'registry.bkp.old']
# x = os.path.isdir("mydir")
# print(x)
# True
# os.rmdir("mydir")
# x = os.listdir(os.curdir)
# print(x)
# ['a.tmp', '1.tmp', '7.tmp', '9.tmp', 'registry.bkp.old']
new_path = cur_path.joinpath("C:", "Log")
print(
new_path.iterdir()
) # iterdir方法类似于os.path.listdir函数,但返回的是路径迭代器而不是字符串列表:
x = list(new_path.iterdir())
print(x)
# [WindowsPath('book1.doc.tmp'), WindowsPath('a.tmp'), WindowsPath('1.tmp'), WindowsPath('7.tmp'), WindowsPath('9.tmp'), WindowsPath('registry.bkp')]
x = list(cur_path.glob("*"))
print(x)
# [WindowsPath('book1.doc.tmp'), WindowsPath('a.tmp'), WindowsPath('1.tmp'), WindowsPath('7.tmp'), WindowsPath('9.tmp'), WindowsPath('registry.bkp')]
x = list(cur_path.glob("*bkp"))
print(x)
# [WindowsPath('registry.bkp')]
x = list(cur_path.glob("?.tmp"))
print(x)
# [WindowsPath('a.tmp'), WindowsPath('1.tmp'), WindowsPath('7.tmp'), WindowsPath('9.tmp')]
x = list(cur_path.glob("[0-9].tmp"))
print(x)
# [WindowsPath('1.tmp'), WindowsPath('7.tmp'), WindowsPath('9.tmp')]
# old_path = Path("registry.bkp")
# new_path = Path("registry.bkp.old")
# old_path.rename(new_path)
x = list(cur_path.iterdir())
print(x)
# [WindowsPath('book1.doc.tmp'), WindowsPath('a.tmp'), WindowsPath('1.tmp'), WindowsPath('7.tmp'), WindowsPath('9.tmp'), WindowsPath('registry.bkp.old')]
# new_path = Path("test")
# new_path.unlink()
# list(cur_path.iterdir())
# [WindowsPath('a.tmp'), WindowsPath('1.tmp'), WindowsPath('7.tmp'), WindowsPath('9.tmp'), WindowsPath('registry.bkp.old')]
# new_path = Path("mydir")
# new_path.mkdir(parents=True)
# list(cur_path.iterdir())
# [WindowsPath('mydir'), WindowsPath('a.tmp'), WindowsPath('1.tmp'), WindowsPath('7.tmp'), WindowsPath('9.tmp'), WindowsPath('registry.bkp.old')]]
# new_path.is_dir('mydir')
# True
# new_path = Path("mydir")
# new_path.rmdir()
# list(cur_path.iterdir())
# [WindowsPath('a.tmp'), WindowsPath('1.tmp'), WindowsPath('7.tmp'), WindowsPath('9.tmp'), WindowsPath('registry.bkp.old']
# 研究题
# 如何计算所有以.txt结尾文件的总大小,符号链接文件除外?
# 如果先用了os.path,请用pathlib再试一遍,反之亦然。
print("--------------------------------")
x = glob.glob("*.txt")
print(x)
y = sum(os.path.getsize(i) for i in x if not os.path.islink(i) and i.is_file())
print(y)
x = list(cur_path.glob("*.txt"))
print(x)
y = sum(getsize(i.name) for i in x if not i.is_symlink() and i.is_file())
# y = sum(i.stat().st_size for i in x if not i.is_symlink())
print(y)
x = list(cur_path.glob("*.txt"))
print(x)
# new_path = Path("APP")
# new_path = cur_path / "APP"
# new_path = cur_path.joinpath("APP")
new_path.mkdir(parents=True, exist_ok=True)
for i in x:
if not i.is_symlink():
old_path = Path(i.name)
new_path = Path(cur_path.joinpath("APP", i.name))
old_path.rename(new_path)
# 4、walk
import os
for root, dirs, files in os.walk(os.curdir):
print("{0} has {1} files".format(root, len(files)))
if ".git" in dirs: # A
dirs.remove(".git") # B
- 10
查看代码 file
py
# 1 打开文件
with open("myfile", "r") as file_object:
line = file_object.readline()
print(line)
line = file_object.readline()
print(line)
# import os
# file_name = os.path.join("c:", "My Documents", "test", "myfile")
# file_object = open(file_name, 'r')
# 2 关闭文件
file_object = open("myfile", "r")
line = file_object.readline()
print(line)
# . . . any further reading on the file_object . . .
file_object.close()
with open("myfile", "r") as file_object:
line = file_object.readline()
# . . . any further reading on the file_object . .
# 3、写入文件
file_object = open("myfile", "w")
file_object.write("Hello, World\n")
file_object.close()
# 4 二进制
## readline
file_object = open("myfile", "r")
count = 0
while file_object.readline() != "":
count = count + 1
print(count)
file_object.close()
## readlines
file_object = open("myfile", "r")
print(len(file_object.readlines()))
file_object.close()
## for in
file_object = open("myfile", "r")
count = 0
for line in file_object:
count = count + 1
print(count)
file_object.close()
## rb read
input_file = open("myfile", "rb")
header = input_file.read(4)
print(header)
# b'Hell'
data = input_file.read()
print(data)
# b'o, World\r\n'
input_file.close()
# readlines -> writelines
input_file = open("myfile", "r")
lines = input_file.readlines()
input_file.close()
output = open("myfile2.txt", "w")
output.writelines(lines)
output.close()
# 5、pathlib
from pathlib import Path
p_text = Path("my_text_file")
p_text.write_text("Text file contents")
# 18
x = p_text.read_text()
print(x)
# 'Text file contents'
p_binary = Path("my_binary_file")
p_binary.write_bytes(b"Binary file contents")
x = p_binary.read_bytes()
print(x)
# b'Binary file contents'
# 6 input/output
# x = input("enter file name to use: ")
# # enter file name to use: myfile
# print(x)
# # 'myfile'
# x = int(input("enter your number: "))
# # enter your number: 39
# print(x)
# # 39
# 7、标准输入、输出重定向
# python 11file.py > myfile < myfile
# python 11file.py < myfile
# python 11file.py
# import sys
# print("Write to the standard output.")
# # Write to the standard output.
# sys.stdout.write("Write to the standard output.\n")
# # Write to the standard output.
# # 30 # 在IDLE会显示 #A
# s = sys.stdin.readline() # 输入内容 + \n
# # An input line
# print("222" + "1")
# print(s + "1")
# # 'An input line\n'
## 重置sys.stdout
# import sys
# f = open("outfile.txt", "w")
# sys.stdout = f
# sys.stdout.writelines(["A first line.\n", "A second line.\n"]) # A
# print("A line from the print function")
# 3 + 4 # B
# sys.stdout = sys.__stdout__
# f.close()
# 3 + 4
# # 7
## print传参file
# import sys
# f = open("outfile.txt", "w")
# print("A first line.\n", "A second line.\n", file=f) # A
# 3 + 4
# 7
# f.close()
# 3 + 4
# 7
print("--------------------------------")
# 7 struct
# import struct
# record_format = "hd4s"
# record_size = struct.calcsize(record_format)
# print("record_size", record_size)
# # 20
# result_list = []
# i = 0
# with open("index.exe", "rb") as f:
# while i < 20:
# i += 1
# record = f.read(record_size)
# print(record)
# # b'MZ\x90\x00\x03\x00\x00\x00\x04\x00\x00\x00\xff\xff\x00\x00\xb8\x00\x00\x00'
# # b'\x00\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
# if len(record) < record_size: # 防止最后不足一条记录
# break
# result_list.append(struct.unpack(record_format, record))
# print(result_list)
# # [(23117, 1.39064994160911e-309, b'\xb8\x00\x00\x00'), (0, 0.0, b'\x00\x00\x00\x00'), (0, 0.0, b'\x00\x00\x00\x00'),...]
# import struct
# record_format = "hd4s"
# x = struct.pack(record_format, 7, 3.14, b"gbye")
# print(x)
# # b"\x07\x00\x00\x00\x00\x00\x00\x00\x1f\x85\xebQ\xb8\x1e\t@gbye"
# 8 Pickle
# import pickle
# .
# .
# .
# file = open("state", 'wb')
# pickle.dump(a, file)
# pickle.dump(b, file)
# pickle.dump(c, file)
# file.close()
# import pickle
# file = open("state", 'rb')
# a = pickle.load(file)
# b = pickle.load(file)
# c = pickle.load(file)
# file.close()
# import pickle
# .
# .
# .
# def save_data():
# global a, b, c
# file = open("state", 'w')
# data = {'a': a, 'b': b, 'c': c}
# pickle.dump(data, file)
# file.close()
# def restore_data():
# global a, b, c
# file = open("state", 'r')
# data = pickle.load(file)
# file.close()
# a = data['a']
# b = data['b']
# c = data['c']
# .
# .
# 初始化文件,方便sole.py启用
# import pickle
# file = open("solecache",'wb')
# pickle.dump({}, file)
# file.close()
# 9 Shelve
import shelve
book = shelve.open("addresses")
book["flintstone"] = ("fred", "555-1234", "1233 Bedrock Place")
book["rubble"] = ("barney", "555-4321", "1235 Bedrock Place")
book.close()
book = shelve.open("addresses")
print(book["flintstone"])
# ('fred', '555-1234', '1233 Bedrock Place')
- 12
查看代码 error
py
# 报错处理
# const ERROR = 1;
# const OK = 0;
# int save_to_file(filename) {
# int status;
# status = save_prefs_to_file(filename);
# if (status == ERROR) {
# ...handle the error...
# }
# status = save_text_to_file(filename);
# if (status == ERROR) {
# ...handle the error...
# }
# status = save_formats_to_file(filename);
# if (status == ERROR) {
# ...handle the error...
# }
# .
# .
# .
# }
# int save_text_to_file(filename) {
# int status;
# status = ...lower-level call to write size of text...
# if (status == ERROR) {
# return(ERROR);
# }
# status = ...lower-level call to write actual text data...
# if (status == ERROR) {
# return(ERROR);
# }
# .
# .
# .
# }
# def save_to_file(filename)
# try to execute the following block
# save_text_to_file(filename)
# save_formats_to_file(filename)
# save_prefs_to_file(filename)
# .
# .
# .
# except that, if the disk runs out of space while
# executing the above block, do this
# ...handle the error...
# def save_text_to_file(filename)
# ...lower-level call to write size of text...
# ...lower-level call to write actual text data...
# .
# .
# .
# 1、raise
alist = [1, 2, 3]
# element = alist[7]
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# IndexError: list index out of range
# raise IndexError("Just kidding")
# Traceback (innermost last):
# File "<stdin>", line 1, in ?
# IndexError: Just kidding
# 2、try except finally
# try:
# body
# except exception_type1 as var1:
# exception_code1
# except exception_type2 as var2:
# exception_code2
# .
# .
# .
# except:
# default_exception_code
# else:
# else_body
# finally:
# finally_body
# 动手题
# try:
# x = int(input("1"))
# y = int(input("2"))
# z = x / y
# print(z)
# except ZeroDivisionError as e:
# print("Error", e)
# finally:
# print("Finally")
# 3、自定义异常
class MyError(Exception):
pass
# raise MyError("Some information about what went wrong")
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# __main__.MyError: Some information about what went wrong
# try:
# raise MyError("Some information about what went wrong")
# except MyError as error:
# print("Situation:", error)
# try:
# raise MyError("Some information", "my_filename", 3)
# # raise Exception("Some information", "my_filename", 3)
# except Exception as e:
# print("Exception:", e)
# except MyError as error:
# print("MyError:", error)
# print(
# "Situation: {0} with file {1}\n error code: {2}".format(
# error.args[0], error.args[1], error.args[2]
# )
# )
# 4、assert
x = (1, 2, 3)
# assert len(x) > 5
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AssertionError: len(x) not > 5
# 动手题
# python -O 12error.py 执行不触发断言
# 14.2.6 Exception inheritance hierarchy
# try:
# body
# except LookupError as error:
# exception code
# except IndexError as error:
# exception code
# 5、正常计算过程中的异常
# def cell_value(string):
# try:
# return float(string)
# except ValueError:
# if string == "":
# return 0
# else:
# return None
# def safe_apply(function, x, y, spreadsheet):
# try:
# return function(x, y, spreadsheet)
# except TypeError:
# return None
# 速测题
try:
y = {}
y[0] = "Hello"
print(y[1])
except KeyError as e:
print("KeyError", e)
x = 1
print(x)
# 6、with 上下文管理器
# try:
# infile = open(filename)
# data = infile.read()
# finally:
# infile.close()
# with open(filename) as infile:
# data = infile.read()