Commit 703a9c16 authored by jackfrued's avatar jackfrued

update so many files

parent 8cc34921
"""
输入学生考试成绩计算平均分
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
number = int(input('请输入学生人数: '))
names = [None] * number
scores = [None] * number
for index in range(len(names)):
names[index] = input('请输入第%d个学生的名字: ' % (index + 1))
scores[index] = float(input('请输入第%d个学生的成绩: ' % (index + 1)))
total = 0
for index in range(len(names)):
print('%s: %.1f分' % (names[index], scores[index]))
total += scores[index]
print('平均成绩是: %.1f分' % (total / number))
if __name__ == '__main__':
main()
"""
定义和使用字典
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
print(scores['骆昊'])
print(scores['狄仁杰'])
for elem in scores:
print('%s\t--->\t%d' % (elem, scores[elem]))
scores['白元芳'] = 65
scores['诸葛王朗'] = 71
scores.update(冷面=67, 方启鹤=85)
print(scores)
if '武则天' in scores:
print(scores['武则天'])
print(scores.get('武则天'))
print(scores.get('武则天', 60))
print(scores.popitem())
print(scores.popitem())
print(scores.pop('骆昊', 100))
scores.clear()
print(scores)
if __name__ == '__main__':
main()
"""
字典的常用操作
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
stu = {'name': '骆昊', 'age': 38, 'gender': True}
print(stu)
print(stu.keys())
print(stu.values())
print(stu.items())
for elem in stu.items():
print(elem)
print(elem[0], elem[1])
if 'age' in stu:
stu['age'] = 20
print(stu)
stu.setdefault('score', 60)
print(stu)
stu.setdefault('score', 100)
print(stu)
stu['score'] = 100
print(stu)
if __name__ == '__main__':
main()
"""
生成斐波拉切数列
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
f = [1 , 1]
for i in range(2, 20):
f += [f[i - 1] + f[i - 2]]
# f.append(f[i - 1] + f[i - 2])
for val in f:
print(val, end=' ')
if __name__ == '__main__':
main()
"""
找出列表中最大或最小的元素
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
fruits = ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya']
# 直接使用内置的max和min函数找出列表中最大和最小元素
# print(max(fruits))
# print(min(fruits))
max_value = min_value = fruits[0]
for index in range(1, len(fruits)):
if fruits[index] > max_value:
max_value = fruits[index]
elif fruits[index] < min_value:
min_value = fruits[index]
print('Max:', max_value)
print('Min:', min_value)
if __name__ == '__main__':
main()
# 想一想如果最大的元素有两个要找出第二大的又该怎么做
"""
定义和使用列表
- 用下标访问元素
- 添加元素
- 删除元素
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
fruits = ['grape', '@pple', 'strawberry', 'waxberry']
print(fruits)
# 通过下标访问元素
print(fruits[0])
print(fruits[1])
print(fruits[-1])
print(fruits[-2])
# print(fruits[-5]) # IndexError
# print(fruits[4]) # IndexError
fruits[1] = 'apple'
print(fruits)
# 添加元素
fruits.append('pitaya')
fruits.insert(0, 'banana')
print(fruits)
# 删除元素
del fruits[1]
fruits.pop()
fruits.pop(0)
fruits.remove('apple')
print(fruits)
if __name__ == '__main__':
main()
"""
列表常用操作
- 列表连接
- 获取长度
- 遍历列表
- 列表切片
- 列表排序
- 列表反转
- 查找元素
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
fruits = ['grape', 'apple', 'strawberry', 'waxberry']
fruits += ['pitaya', 'pear', 'mango']
# 循环遍历列表元素
for fruit in fruits:
print(fruit.title(), end=' ')
print()
# 列表切片
fruits2 = fruits[1:4]
print(fruits2)
# fruit3 = fruits # 没有复制列表只创建了新的引用
fruits3 = fruits[:]
print(fruits3)
fruits4 = fruits[-3:-1]
print(fruits4)
fruits5 = fruits[::-1]
print(fruits5)
if __name__ == '__main__':
main()
"""
生成列表
- 用range创建数字列表
- 生成表达式
- 生成器
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
# 生成Fibonacci序列的生成器
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
yield a
def main():
# 用range创建数值列表
list1 = list(range(1, 11))
print(list1)
# 生成表达式
list2 = [x * x for x in range(1, 11)]
print(list2)
list3 = [m + n for m in 'ABCDEFG' for n in '12345']
print(list3)
print(len(list3))
# 生成器(节省空间但生成下一个元素时需要花费时间)
gen = (m + n for m in 'ABCDEFG' for n in '12345')
print(gen)
for elem in gen:
print(elem, end=' ')
print()
gen = fib(20)
print(gen)
for elem in gen:
print(elem, end=' ')
print()
if __name__ == '__main__':
main()
"""
双色球随机选号程序
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
from random import randrange, randint, sample
def display(balls):
"""
输出列表中的双色球号码
"""
for index, ball in enumerate(balls):
if index == len(balls) - 1:
print('|', end=' ')
print('%02d' % ball, end=' ')
print()
def random_select():
"""
随机选择一组号码
"""
red_balls = [x for x in range(1, 34)]
selected_balls = []
for _ in range(6):
index = randrange(len(red_balls))
selected_balls.append(red_balls[index])
del red_balls[index]
# 上面的for循环也可以写成下面这行代码
# sample函数是random模块下的函数
# selected_balls = sample(red_balls, 6)
selected_balls.sort()
selected_balls.append(randint(1, 16))
return selected_balls
def main():
n = int(input('机选几注: '))
for _ in range(n):
display(random_select())
if __name__ == '__main__':
main()
"""
输入学生考试成绩计算平均分
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
import os
import time
def main():
str = 'Welcome to 1000 Phone Chengdu Campus '
while True:
print(str)
time.sleep(0.2)
str = str[1:] + str[0:1]
# for Windows use os.system('cls') instead
os.system('clear')
if __name__ == '__main__':
main()
"""
学生考试成绩表
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
names = ['关羽', '张飞', '赵云', '马超', '黄忠']
subjs = ['语文', '数学', '英语']
scores = [[0] * 3] * 5
for row, name in enumerate(names):
print('请输入%s的成绩' % name)
for col, subj in enumerate(subjs):
scores[row][col] = float(input(subj + ': '))
print(scores)
# for row, name in enumerate(names):
# print('请输入%s的成绩' % name)
# scores[row] = [None] * len(subjs)
# for col, subj in enumerate(subjs):
# score = float(input(subj + ': '))
# scores[row][col] = score
# print(scores)
if __name__ == '__main__':
main()
"""
定义和使用集合
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
set1 = {1, 2, 3, 3, 3, 2}
print(set1)
print('Length =', len(set1))
set2 = set(range(1, 10))
print(set2)
set1.add(4)
set1.add(5)
set2.update([11, 12])
print(set1)
print(set2)
set2.discard(5)
# remove的元素如果不存在会引发KeyError
if 4 in set2:
set2.remove(4)
print(set2)
# 遍历集合容器
for elem in set2:
print(elem ** 2, end=' ')
print()
# 将元组转换成集合
set3 = set((1, 2, 3, 3, 2, 1))
print(set3.pop())
print(set3)
if __name__ == '__main__':
main()
"""
集合的常用操作
- 交集
- 并集
- 差集
- 子集
- 超集
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
set1 = set(range(1, 7))
print(set1)
set2 = set(range(2, 11, 2))
print(set2)
set3 = set(range(1, 5))
print(set1 & set2)
# print(set1.intersection(set2))
print(set1 | set2)
# print(set1.union(set2))
print(set1 - set2)
# print(set1.difference(set2))
print(set1 ^ set2)
# print(set1.symmetric_difference(set2))
print(set2 <= set1)
# print(set2.issubset(set1))
print(set3 <= set1)
# print(set3.issubset(set1))
print(set1 >= set2)
# print(set1.issuperset(set2))
print(set1 >= set3)
# print(set1.issuperset(set3))
if __name__ == '__main__':
main()
"""
井字棋游戏
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
import os
def print_board(board):
print(board['TL'] + '|' + board['TM'] + '|' + board['TR'])
print('-+-+-')
print(board['ML'] + '|' + board['MM'] + '|' + board['MR'])
print('-+-+-')
print(board['BL'] + '|' + board['BM'] + '|' + board['BR'])
def main():
init_board = {
'TL': ' ', 'TM': ' ', 'TR': ' ',
'ML': ' ', 'MM': ' ', 'MR': ' ',
'BL': ' ', 'BM': ' ', 'BR': ' '
}
begin = True
while begin:
curr_board = init_board.copy()
begin = False
turn = 'x'
counter = 0
os.system('clear')
print_board(curr_board)
while counter < 9:
move = input('轮到%s走棋, 请输入位置: ' % turn)
if curr_board[move] == ' ':
counter += 1
curr_board[move] = turn
if turn == 'x':
turn = 'o'
else:
turn = 'x'
os.system('clear')
print_board(curr_board)
choice = input('再玩一局?(yes|no)')
begin = choice == 'yes'
if __name__ == '__main__':
main()
"""
元组的定义和使用
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
# 定义元组
t = ('骆昊', 38, True, '四川成都')
print(t)
# 获取元组中的元素
print(t[0])
print(t[1])
print(t[2])
print(t[3])
# 遍历元组中的值
for member in t:
print(member)
# 重新给元组赋值
# t[0] = '王大锤' # TypeError
# 变量t重新引用了新的元组 原来的元组被垃圾回收
t = ('王大锤', 20, True, '云南昆明')
print(t)
# 元组和列表的转换
person = list(t)
print(person)
person[0] = '李小龙'
person[1] = 25
print(person)
fruits_list = ['apple', 'banana', 'orange']
fruits_tuple = tuple(fruits_list)
print(fruits_tuple)
print(fruits_tuple[1])
if __name__ == '__main__':
main()
\ No newline at end of file
"""
输出10行的杨辉三角 - 二项式的n次方展开系数
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
... ... ...
Version: 0.1
Author: 骆昊
Date: 2018-03-06
"""
def main():
num = int(input('Number of rows: '))
yh = [[]] * num
for row in range(len(yh)):
yh[row] = [None] * (row + 1)
for col in range(len(yh[row])):
if col == 0 or col == row:
yh[row][col] = 1
else:
yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]
print(yh[row][col], end='\t')
print()
if __name__ == '__main__':
main()
This diff is collapsed.
class Test:
def __init__(self, foo):
self.__foo = foo
def __bar(self):
print(self.__foo)
print('__bar')
def main():
test = Test('hello')
test._Test__bar()
print(test._Test__foo)
if __name__ == "__main__":
main()
"""
练习
修一个游泳池 半径(以米为单位)在程序运行时输入 游泳池外修一条3米宽的过道
过道的外侧修一圈围墙 已知过道的造价为25元每平米 围墙的造价为32.5元每米
输出围墙和过道的总造价分别是多少钱(精确到小数点后2位)
Version: 0.1
Author: 骆昊
Date: 2018-03-08
"""
import math
class Circle(object):
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, radius):
self._radius = radius if radius > 0 else 0
@property
def perimeter(self):
return 2 * math.pi * self._radius
@property
def area(self):
return math.pi * self._radius * self._radius
if __name__ == '__main__':
radius = float(input('请输入游泳池的半径: '))
small = Circle(radius)
big = Circle(radius + 3)
print('围墙的造价为: ¥%.1f元' % (big.perimeter * 115))
print('过道的造价为: ¥%.1f元' % ((big.area - small.area) * 65))
"""
定义和使用时钟类
Version: 0.1
Author: 骆昊
Date: 2018-03-08
"""
import time
import os
class Clock(object):
# Python中的函数是没有重载的概念的
# 因为Python中函数的参数没有类型而且支持缺省参数和可变参数
# 用关键字参数让构造器可以传入任意多个参数来实现其他语言中的构造器重载
def __init__(self, **kw):
if 'hour' in kw and 'minute' in kw and 'second' in kw:
self._hour = kw['hour']
self._minute = kw['minute']
self._second = kw['second']
else:
tm = time.localtime(time.time())
self._hour = tm.tm_hour
self._minute = tm.tm_min
self._second = tm.tm_sec
def run(self):
self._second += 1
if self._second == 60:
self._second = 0
self._minute += 1
if self._minute == 60:
self._minute = 0
self._hour += 1
if self._hour == 24:
self._hour = 0
def show(self):
return '%02d:%02d:%02d' % (self._hour, self._minute, self._second)
if __name__ == '__main__':
# clock = Clock(hour=10, minute=5, second=58)
clock = Clock()
while True:
os.system('clear')
print(clock.show())
time.sleep(1)
clock.run()
"""
面向对象版本的猜数字游戏
Version: 0.1
Author: 骆昊
Date: 2018-03-08
"""
from random import randint
class GuessMachine(object):
def __init__(self):
self._answer = None
self._counter = None
self._hint = None
def reset(self):
self._answer = randint(1, 100)
self._counter = 0
self._hint = None
def guess(self, your_answer):
self._counter += 1
if your_answer > self._answer:
self._hint = '小一点'
elif your_answer < self._answer:
self._hint = '大一点'
else:
self._hint = '恭喜你猜对了'
return True
return False
@property
def counter(self):
return self._counter
@property
def hint(self):
return self._hint
if __name__ == '__main__':
gm = GuessMachine()
play_again = True
while play_again:
game_over = False
gm.reset()
while not game_over:
your_answer = int(input('请输入: '))
game_over = gm.guess(your_answer)
print(gm.hint)
if gm.counter > 7:
print('智商余额不足!')
play_again = input('再玩一次?(yes|no)') == 'yes'
"""
另一种创建类的方式
Version: 0.1
Author: 骆昊
Date: 2018-03-08
"""
def bar(self, name):
self._name = name
def foo(self, course_name):
print('%s正在学习%s.' % (self._name, course_name))
def main():
Student = type('Student', (object,), dict(__init__=bar, study=foo))
stu1 = Student('骆昊')
stu1.study('Python程序设计')
if __name__ == '__main__':
main()
"""
定义和使用矩形类
Version: 0.1
Author: 骆昊
Date: 2018-03-08
"""
class Rect(object):
"""矩形类"""
def __init__(self, width=0, height=0):
"""构造器"""
self.__width = width
self.__height = height
def perimeter(self):
"""计算周长"""
return (self.__width + self.__height) * 2
def area(self):
"""计算面积"""
return self.__width * self.__height
def __str__(self):
"""矩形对象的字符串表达式"""
return '矩形[%f,%f]' % (self.__width, self.__height)
def __del__(self):
"""析构器"""
print('销毁矩形对象')
if __name__ == '__main__':
rect1 = Rect()
print(rect1)
print(rect1.perimeter())
print(rect1.area())
rect2 = Rect(3.5, 4.5)
print(rect2)
print(rect2.perimeter())
print(rect2.area())
"""
定义和使用学生类
Version: 0.1
Author: 骆昊
Date: 2018-03-08
"""
def _foo():
print('test')
class Student(object):
# __init__是一个特殊方法用于在创建对象时进行初始化操作
# 通过这个方法我们可以为学生对象绑定name和age两个属性
def __init__(self, name, age):
self.name = name
self.age = age
def study(self, course_name):
print('%s正在学习%s.' % (self.name, course_name))
# PEP 8要求标识符的名字用全小写多个单词用下划线连接
# 但是很多程序员和公司更倾向于使用驼峰命名法(驼峰标识)
def watch_av(self):
if self.age < 18:
print('%s只能观看《熊出没》.' % self.name)
else:
print('%s正在观看岛国爱情动作片.' % self.name)
def main():
stu1 = Student('骆昊', 38)
stu1.study('Python程序设计')
stu1.watch_av()
stu2 = Student('王大锤', 15)
stu2.study('思想品德')
stu2.watch_av()
if __name__ == '__main__':
main()
\ No newline at end of file
This diff is collapsed.
"""
对象之间的关联关系
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
from math import sqrt
class Point(object):
def __init__(self, x=0, y=0):
self._x = x
self._y = y
def move_to(self, x, y):
self._x = x
self._y = y
def move_by(self, dx, dy):
self._x += dx
self._y += dy
def distance_to(self, other):
dx = self._x - other._x
dy = self._y - other._y
return sqrt(dx ** 2 + dy ** 2)
def __str__(self):
return '(%s, %s)' % (str(self._x), str(self._y))
class Line(object):
def __init__(self, start=Point(0, 0), end=Point(0, 0)):
self._start = start
self._end = end
@property
def start(self):
return self._start
@start.setter
def start(self, start):
self._start = start
@property
def end(self):
return self.end
@end.setter
def end(self, end):
self._end = end
@property
def length(self):
return self._start.distance_to(self._end)
if __name__ == '__main__':
p1 = Point(3, 5)
print(p1)
p2 = Point(-2, -1.5)
print(p2)
line = Line(p1, p2)
print(line.length)
line.start.move_to(2, 1)
line.end = Point(1, 2)
print(line.length)
"""
属性的使用
- 访问器/修改器/删除器
- 使用__slots__对属性加以限制
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
class Car(object):
__slots__ = ('_brand', '_max_speed')
def __init__(self, brand, max_speed):
self._brand = brand
self._max_speed = max_speed
@property
def brand(self):
return self._brand
@brand.setter
def brand(self, brand):
self._brand = brand
@brand.deleter
def brand(self):
del self._brand
@property
def max_speed(self):
return self._max_speed
@max_speed.setter
def max_speed(self, max_speed):
if max_speed < 0:
raise ValueError('Invalid max speed for car')
self._max_speed = max_speed
def __str__(self):
return 'Car: [品牌=%s, 最高时速=%d]' % (self._brand, self._max_speed)
car = Car('QQ', 120)
print(car)
# ValueError
# car.max_speed = -100
car.max_speed = 320
car.brand = "Benz"
# 使用__slots__属性限制后下面的代码将产生异常
# car.current_speed = 80
print(car)
# 如果提供了删除器可以执行下面的代码
# del car.brand
# 属性的实现
print(Car.brand)
print(Car.brand.fget)
print(Car.brand.fset)
print(Car.brand.fdel)
# 通过上面的代码帮助学生理解之前提到的包装器的概念
# Python中有很多类似的语法糖后面还会出现这样的东西
"""
属性的使用
- 使用已有方法定义访问器/修改器/删除器
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
class Car(object):
def __init__(self, brand, max_speed):
self.set_brand(brand)
self.set_max_speed(max_speed)
def get_brand(self):
return self._brand
def set_brand(self, brand):
self._brand = brand
def get_max_speed(self):
return self._max_speed
def set_max_speed(self, max_speed):
if max_speed < 0:
raise ValueError('Invalid max speed for car')
self._max_speed = max_speed
def __str__(self):
return 'Car: [品牌=%s, 最高时速=%d]' % (self._brand, self._max_speed)
# 用已有的修改器和访问器定义属性
brand = property(get_brand, set_brand)
max_speed = property(get_max_speed, set_max_speed)
car = Car('QQ', 120)
print(car)
# ValueError
# car.max_speed = -100
car.max_speed = 320
car.brand = "Benz"
print(car)
print(Car.brand)
print(Car.brand.fget)
print(Car.brand.fset)
from time import time, localtime, sleep
class Clock(object):
"""数字时钟"""
def __init__(self, hour=0, minute=0, second=0):
self._hour = hour
self._minute = minute
self._second = second
@classmethod
def now(cls):
ctime = localtime(time())
return cls(ctime.tm_hour, ctime.tm_min, ctime.tm_sec)
def run(self):
"""走字"""
self._second += 1
if self._second == 60:
self._second = 0
self._minute += 1
if self._minute == 60:
self._minute = 0
self._hour += 1
if self._hour == 24:
self._hour = 0
def show(self):
"""显示时间"""
return '%02d:%02d:%02d' % \
(self._hour, self._minute, self._second)
def main():
clock = Clock.now()
while True:
print(clock.show())
sleep(1)
clock.run()
if __name__ == '__main__':
main()
"""
对象之间的依赖关系和运算符重载
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
class Car(object):
def __init__(self, brand, max_speed):
self._brand = brand
self._max_speed = max_speed
self._current_speed = 0
@property
def brand(self):
return self._brand
def accelerate(self, delta):
self._current_speed += delta
if self._current_speed > self._max_speed:
self._current_speed = self._max_speed
def brake(self):
self._current_speed = 0
def __str__(self):
return '%s当前时速%d' % (self._brand, self._current_speed)
class Student(object):
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
# 学生和车之间存在依赖关系 - 学生使用了汽车
def drive(self, car):
print('%s驾驶着%s欢快的行驶在去西天的路上' % (self._name, car._brand))
car.accelerate(30)
print(car)
car.accelerate(50)
print(car)
car.accelerate(50)
print(car)
def study(self, course_name):
print('%s正在学习%s.' % (self._name, course_name))
def watch_av(self):
if self._age < 18:
print('%s只能观看《熊出没》.' % self._name)
else:
print('%s正在观看岛国爱情动作片.' % self._name)
# 重载大于(>)运算符
def __gt__(self, other):
return self._age > other._age
# 重载小于(<)运算符
def __lt__(self, other):
return self._age < other._age
if __name__ == '__main__':
stu1 = Student('骆昊', 38)
stu1.study('Python程序设计')
stu1.watch_av()
stu2 = Student('王大锤', 15)
stu2.study('思想品德')
stu2.watch_av()
car = Car('QQ', 120)
stu2.drive(car)
print(stu1 > stu2)
print(stu1 < stu2)
"""
多重继承
- 菱形继承(钻石继承)
- C3算法(替代DFS的算法)
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
class A(object):
def foo(self):
print('foo of A')
class B(A):
pass
class C(A):
def foo(self):
print('foo fo C')
class D(B, C):
pass
class E(D):
def foo(self):
print('foo in E')
super().foo()
super(B, self).foo()
super(C, self).foo()
if __name__ == '__main__':
d = D()
d.foo()
e = E()
e.foo()
"""
抽象类 / 方法重写 / 多态
实现一个工资结算系统 公司有三种类型的员工
- 部门经理固定月薪12000元/月
- 程序员按本月工作小时数每小时100元
- 销售员1500元/月的底薪加上本月销售额5%的提成
输入员工的信息 输出每位员工的月薪信息
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
from abc import ABCMeta, abstractmethod
class Employee(object, metaclass=ABCMeta):
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@abstractmethod
def get_salary(self):
pass
class Manager(Employee):
# 想一想: 如果不定义构造方法会怎么样
def __init__(self, name):
# 想一想: 如果不调用父类构造器会怎么样
super().__init__(name)
def get_salary(self):
return 12000
class Programmer(Employee):
def __init__(self, name):
super().__init__(name)
def set_working_hour(self, working_hour):
self._working_hour = working_hour
def get_salary(self):
return 100 * self._working_hour
class Salesman(Employee):
def __init__(self, name):
super().__init__(name)
def set_sales(self, sales):
self._sales = sales
def get_salary(self):
return 1500 + self._sales * 0.05
if __name__ == '__main__':
emps = [Manager('武则天'), Programmer('狄仁杰'), Salesman('白元芳')]
for emp in emps:
if isinstance(emp, Programmer):
working_hour = int(input('请输入%s本月工作时间: ' % emp.name))
emp.set_working_hour(working_hour)
elif isinstance(emp, Salesman):
sales = float(input('请输入%s本月销售额: ' % emp.name))
emp.set_sales(sales)
print('%s本月月薪为: ¥%.2f元' % (emp.name, emp.get_salary()))
"""
多重继承
- 通过多重继承可以给一个类的对象具备多方面的能力
- 这样在设计类的时候可以避免设计太多层次的复杂的继承关系
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
class Father(object):
def __init__(self, name):
self._name = name
def gamble(self):
print('%s在打麻将.' % self._name)
def eat(self):
print('%s在大吃大喝.' % self._name)
class Monk(object):
def __init__(self, name):
self._name = name
def eat(self):
print('%s在吃斋.' % self._name)
def chant(self):
print('%s在念经.' % self._name)
class Musician(object):
def __init__(self, name):
self._name = name
def eat(self):
print('%s在细嚼慢咽.' % self._name)
def play_piano(self):
print('%s在弹钢琴.' % self._name)
# 试一试下面的代码看看有什么区别
# class Son(Monk, Father, Musician):
# class Son(Musician, Father, Monk):
class Son(Father, Monk, Musician):
def __init__(self, name):
Father.__init__(self, name)
Monk.__init__(self, name)
Musician.__init__(self, name)
son = Son('王大锤')
son.gamble()
# 调用继承自Father的eat方法
son.eat()
son.chant()
son.play_piano()
from abc import ABCMeta, abstractmethod
class Pet(object, metaclass=ABCMeta):
def __init__(self, nickname):
self._nickname = nickname
@abstractmethod
def make_voice(self):
pass
class Dog(Pet):
def make_voice(self):
print('%s: 汪汪汪...' % self._nickname)
class Cat(Pet):
def make_voice(self):
print('%s: 喵...喵...' % self._nickname)
def main():
pets = [Dog('旺财'), Cat('凯蒂'), Dog('大黄')]
for pet in pets:
pet.make_voice()
if __name__ == '__main__':
main()
"""
运算符重载 - 自定义分数类
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
from math import gcd
class Rational(object):
def __init__(self, num, den=1):
if den == 0:
raise ValueError('分母不能为0')
self._num = num
self._den = den
self.normalize()
def simplify(self):
x = abs(self._num)
y = abs(self._den)
factor = gcd(x, y)
if factor > 1:
self._num //= factor
self._den //= factor
return self
def normalize(self):
if self._den < 0:
self._den = -self._den
self._num = -self._num
return self
def __add__(self, other):
new_num = self._num * other._den + other._num * self._den
new_den = self._den * other._den
return Rational(new_num, new_den).simplify().normalize()
def __sub__(self, other):
new_num = self._num * other._den - other._num * self._den
new_den = self._den * other._den
return Rational(new_num, new_den).simplify().normalize()
def __mul__(self, other):
new_num = self._num * other._num
new_den = self._den * other._den
return Rational(new_num, new_den).simplify().normalize()
def __truediv__(self, other):
new_num = self._num * other._den
new_den = self._den * other._num
return Rational(new_num, new_den).simplify().normalize()
def __str__(self):
if self._num == 0:
return '0'
elif self._den == 1:
return str(self._num)
else:
return '(%d/%d)' % (self._num, self._den)
if __name__ == '__main__':
r1 = Rational(2, 3)
print(r1)
r2 = Rational(6, -8)
print(r2)
print(r2.simplify())
print('%s + %s = %s' % (r1, r2, r1 + r2))
print('%s - %s = %s' % (r1, r2, r1 - r2))
print('%s * %s = %s' % (r1, r2, r1 * r2))
print('%s / %s = %s' % (r1, r2, r1 / r2))
This diff is collapsed.
"""
继承的应用
- 抽象类
- 抽象方法
- 方法重写
- 多态
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
from abc import ABCMeta, abstractmethod
from math import pi
class Shape(object, metaclass=ABCMeta):
@abstractmethod
def perimeter(self):
pass
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self._radius = radius
def perimeter(self):
return 2 * pi * self._radius
def area(self):
return pi * self._radius ** 2
def __str__(self):
return '我是一个圆'
class Rect(Shape):
def __init__(self, width, height):
self._width = width
self._height = height
def perimeter(self):
return 2 * (self._width + self._height)
def area(self):
return self._width * self._height
def __str__(self):
return '我是一个矩形'
if __name__ == '__main__':
shapes = [Circle(5), Circle(3.2), Rect(3.2, 6.3)]
for shape in shapes:
print(shape)
print('周长:', shape.perimeter())
print('面积:', shape.area())
"""
实例方法和类方法的应用
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
from math import sqrt
class Triangle(object):
def __init__(self, a, b, c):
self._a = a
self._b = b
self._c = c
# 静态方法
@staticmethod
def is_valid(a, b, c):
return a + b > c and b + c > a and c + a > b
# 实例方法
def perimeter(self):
return self._a + self._b + self._c
# 实例方法
def area(self):
p = self.perimeter() / 2
return sqrt(p * (p - self._a) * (p - self._b) * (p - self._c))
if __name__ == '__main__':
# 用字符串的split方法将字符串拆分成一个列表
# 再通过map函数对列表中的每个字符串进行映射处理成小数
a, b, c = map(float, input('请输入三条边: ').split())
# 先判断给定长度的三条边能否构成三角形
# 如果能才创建三角形对象
if Triangle.is_valid(a, b, c):
tri = Triangle(a, b, c)
print('周长:', tri.perimeter())
print('面积:', tri.area())
# 如果传入对象作为方法参数也可以通过类调用实例方法
# print('周长:', Triangle.perimeter(tri))
# print('面积:', Triangle.area(tri))
# 看看下面的代码就知道其实二者本质上是一致的
# print(type(tri.perimeter))
# print(type(Triangle.perimeter))
else:
print('不能构成三角形.')
This diff is collapsed.
from enum import Enum, unique
from math import sqrt
from random import randint
import pygame
@unique
class Color(Enum):
"""颜色"""
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (242, 242, 242)
@staticmethod
def random_color():
"""获得随机颜色"""
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
return (r, g, b)
class Ball(object):
"""球"""
def __init__(self, x, y, radius, sx, sy, color=Color.RED):
"""初始化方法"""
self.x = x
self.y = y
self.radius = radius
self.sx = sx
self.sy = sy
self.color = color
self.alive = True
def move(self, screen):
"""移动"""
self.x += self.sx
self.y += self.sy
if self.x - self.radius <= 0 or self.x + self.radius >= screen.get_width():
self.sx = -self.sx
if self.y - self.radius <= 0 or self.y + self.radius >= screen.get_height():
self.sy = -self.sy
def eat(self, other):
"""吃其他球"""
if self.alive and other.alive and self != other:
dx, dy = self.x - other.x, self.y - other.y
distance = sqrt(dx ** 2 + dy ** 2)
if distance < self.radius + other.radius \
and self.radius > other.radius:
other.alive = False
self.radius = self.radius + int(other.radius * 0.146)
def draw(self, screen):
"""在窗口上绘制球"""
pygame.draw.circle(screen, self.color,
(self.x, self.y), self.radius, 0)
def main():
# 定义用来装所有球的容器
balls = []
# 初始化导入的pygame中的模块
pygame.init()
# 初始化用于显示的窗口并设置窗口尺寸
screen = pygame.display.set_mode((800, 600))
print(screen.get_width())
print(screen.get_height())
# 设置当前窗口的标题
pygame.display.set_caption('大球吃小球')
# 定义变量来表示小球在屏幕上的位置
x, y = 50, 50
running = True
# 开启一个事件循环处理发生的事件
while running:
# 从消息队列中获取事件并对事件进行处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
x, y = event.pos
radius = randint(10, 100)
sx, sy = randint(-10, 10), randint(-10, 10)
color = Color.random_color()
ball = Ball(x, y, radius, sx, sy, color)
balls.append(ball)
screen.fill((255, 255, 255))
for ball in balls:
if ball.alive:
ball.draw(screen)
else:
balls.remove(ball)
pygame.display.flip()
# 每隔50毫秒就改变小球的位置再刷新窗口
pygame.time.delay(50)
for ball in balls:
ball.move(screen)
for other in balls:
ball.eat(other)
if __name__ == '__main__':
main()
"""
使用tkinter创建GUI
- 顶层窗口
- 控件
- 布局
- 事件回调
Version: 0.1
Author: 骆昊
Date: 2018-03-14
"""
import tkinter
import tkinter.messagebox
def main():
flag = True
# 修改标签上的文字
def change_label_text():
nonlocal flag
flag = not flag
color, msg = ('red', 'Hello, world!')\
if flag else ('blue', 'Goodbye, world!')
label.config(text=msg, fg=color)
# 确认退出
def confirm_to_quit():
if tkinter.messagebox.askokcancel('温馨提示', '确定要退出吗?'):
top.quit()
# 创建顶层窗口
top = tkinter.Tk()
# 设置窗口大小
top.geometry('240x160')
# 设置窗口标题
top.title('小游戏')
# 创建标签对象
label = tkinter.Label(top, text='Hello, world!', font='Arial -32', fg='red')
label.pack(expand=1)
# 创建一个装按钮的容器
panel = tkinter.Frame(top)
# 创建按钮对象
button1 = tkinter.Button(panel, text='修改', command=change_label_text)
button1.pack(side='left')
button2 = tkinter.Button(panel, text='退出', command=confirm_to_quit)
button2.pack(side='right')
panel.pack(side='bottom')
# 开启主事件循环
tkinter.mainloop()
if __name__ == '__main__':
main()
"""
使用tkinter创建GUI
- 使用画布绘图
- 处理鼠标事件
Version: 0.1
Author: 骆昊
Date: 2018-03-14
"""
import tkinter
def mouse_evt_handler(evt=None):
row = round((evt.y - 20) / 40)
col = round((evt.x - 20) / 40)
pos_x = 40 * col
pos_y = 40 * row
canvas.create_oval(pos_x, pos_y, 40 + pos_x, 40 + pos_y, fill='black')
top = tkinter.Tk()
# 设置窗口尺寸
top.geometry('620x620')
# 设置窗口标题
top.title('五子棋')
# 设置窗口大小不可改变
top.resizable(False, False)
# 设置窗口置顶
top.wm_attributes('-topmost', 1)
canvas = tkinter.Canvas(top, width=600, height=600, bd=0, highlightthickness=0)
canvas.bind('<Button-1>', mouse_evt_handler)
canvas.create_rectangle(0, 0, 600, 600, fill='yellow', outline='white')
for index in range(15):
canvas.create_line(20, 20 + 40 * index, 580, 20 + 40 * index, fill='black')
canvas.create_line(20 + 40 * index, 20, 20 + 40 * index, 580, fill='black')
canvas.create_rectangle(15, 15, 585, 585, outline='black', width=4)
canvas.pack()
tkinter.mainloop()
# 请思考如何用面向对象的编程思想对上面的代码进行封装
"""
使用tkinter创建GUI
- 在窗口上制作动画
Version: 0.1
Author: 骆昊
Date: 2018-03-14
"""
import tkinter
import time
# 播放动画效果的函数
def play_animation():
canvas.move(oval, 2, 2)
canvas.update()
top.after(50, play_animation)
x = 10
y = 10
top = tkinter.Tk()
top.geometry('600x600')
top.title('动画效果')
top.resizable(False, False)
top.wm_attributes('-topmost', 1)
canvas = tkinter.Canvas(top, width=600, height=600, bd=0, highlightthickness=0)
canvas.create_rectangle(0, 0, 600, 600, fill='gray')
oval = canvas.create_oval(10, 10, 60, 60, fill='red')
canvas.pack()
top.update()
play_animation()
tkinter.mainloop()
# 请思考如何让小球碰到屏幕的边界就弹回
# 请思考如何用面向对象的编程思想对上面的代码进行封装
"""
用turtle模块绘图
这是一个非常有趣的模块 它模拟一只乌龟在窗口上爬行的方式来进行绘图
Version: 0.1
Author: 骆昊
Date: 2018-03-14
"""
import turtle
turtle.pensize(3)
turtle.penup()
turtle.goto(-180, 150)
turtle.pencolor('red')
turtle.fillcolor('yellow')
turtle.pendown()
turtle.begin_fill()
for _ in range(36):
turtle.forward(200)
turtle.right(170)
turtle.end_fill()
turtle.mainloop()
This diff is collapsed.
"""
读取CSV文件
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
import csv
filename = 'example.csv'
try:
with open(filename) as f:
reader = csv.reader(f)
data = list(reader)
except FileNotFoundError:
print('无法打开文件:', filename)
else:
for item in data:
print('%-30s%-20s%-10s' % (item[0], item[1], item[2]))
"""
写入CSV文件
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
import csv
class Teacher(object):
def __init__(self, name, age, title):
self.__name = name
self.__age = age
self.__title = title
self.__index = -1
@property
def name(self):
return self.__name
@property
def age(self):
return self.__age
@property
def title(self):
return self.__title
filename = 'teacher.csv'
teachers = [Teacher('骆昊', 38, '叫兽'), Teacher('狄仁杰', 25, '砖家')]
try:
with open(filename, 'w') as f:
writer = csv.writer(f)
for teacher in teachers:
writer.writerow([teacher.name, teacher.age, teacher.title])
except BaseException as e:
print('无法写入文件:', filename)
else:
print('保存数据完成!')
"""
异常机制 - 处理程序在运行时可能发生的状态
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
input_again = True
while input_again:
try:
a = int(input('a = '))
b = int(input('b = '))
print('%d / %d = %f' % (a, b, a / b))
input_again = False
except ValueError:
print('请输入整数')
except ZeroDivisionError:
print('除数不能为0')
# 处理异常让代码不因异常而崩溃是一方面
# 更重要的是可以通过对异常的处理让代码从异常中恢复过来
"""
异常机制 - 处理程序在运行时可能发生的状态
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
input_again = True
while input_again:
try:
a = int(input('a = '))
b = int(input('b = '))
print('%d / %d = %f' % (a, b, a / b))
input_again = False
except (ValueError, ZeroDivisionError) as msg:
print(msg)
"""
异常机制 - 处理程序在运行时可能发生的状态
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
import time
import sys
filename = input('请输入文件名: ')
try:
with open(filename) as f:
lines = f.readlines()
except FileNotFoundError as msg:
print('无法打开文件:', filename)
print(msg)
except UnicodeDecodeError as msg:
print('非文本文件无法解码')
sys.exit()
else:
for line in lines:
print(line.rstrip())
time.sleep(0.5)
finally:
# 此处最适合做善后工作
print('不管发生什么我都会执行')
"""
引发异常和异常栈
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
def f1():
raise AssertionError('发生异常')
def f2():
f1()
def f3():
f2()
f3()
4/5/2014 13:34,Apples,73
4/5/2014 3:41,Cherries,85
4/6/2014 12:46,Pears,14
4/8/2014 8:59,Oranges,52
4/10/2014 2:07,Apples,152
4/10/2014 18:10,Bananas,23
4/10/2014 2:40,Strawberries,98
"""
从文本文件中读取数据
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
import time
def main():
# 一次性读取整个文件内容
with open('致橡树.txt', 'r', encoding='utf-8') as f:
print(f.read())
# 通过for-in循环逐行读取
with open('致橡树.txt', mode='r') as f:
for line in f:
print(line, end='')
time.sleep(0.5)
print()
# 读取文件按行读取到列表中
with open('致橡树.txt') as f:
lines = f.readlines()
print(lines)
if __name__ == '__main__':
main()
"""
读取圆周率文件判断其中是否包含自己的生日
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
birth = input('请输入你的生日: ')
with open('pi_million_digits.txt') as f:
lines = f.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
if birth in pi_string:
print('Bingo!!!')
"""
写文本文件
将100以内的素数写入到文件中
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
from math import sqrt
def is_prime(n):
for factor in range(2, int(sqrt(n)) + 1):
if n % factor == 0:
return False
return True
# 试一试有什么不一样
# with open('prime.txt', 'a') as f:
with open('prime.txt', 'w') as f:
for num in range(2, 100):
if is_prime(num):
f.write(str(num) + '\n')
print('写入完成!')
"""
读写二进制文件
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
import base64
with open('mm.jpg', 'rb') as f:
data = f.read()
# print(type(data))
# print(data)
print('字节数:', len(data))
# 将图片处理成BASE-64编码
print(base64.b64encode(data))
with open('girl.jpg', 'wb') as f:
f.write(data)
print('写入完成!')
"""
读取JSON数据
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
import json
import csv2
json_str = '{"name": "骆昊", "age": 38, "title": "叫兽"}'
result = json.loads(json_str)
print(result)
print(type(result))
print(result['name'])
print(result['age'])
# 把转换得到的字典作为关键字参数传入Teacher的构造器
teacher = csv2.Teacher(**result)
print(teacher)
print(teacher.name)
print(teacher.age)
print(teacher.title)
# 请思考如何将下面JSON格式的天气数据转换成对象并获取我们需要的信息
# 稍后我们会讲解如何通过网络API获取我们需要的JSON格式的数据
"""
{
"wendu": "29",
"ganmao": "各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。",
"forecast": [
{
"fengxiang": "南风",
"fengli": "3-4级",
"high": "高温 32℃",
"type": "多云",
"low": "低温 17℃",
"date": "16日星期二"
},
{
"fengxiang": "南风",
"fengli": "微风级",
"high": "高温 34℃",
"type": "晴",
"low": "低温 19℃",
"date": "17日星期三"
},
{
"fengxiang": "南风",
"fengli": "微风级",
"high": "高温 35℃",
"type": "晴",
"low": "低温 22℃",
"date": "18日星期四"
},
{
"fengxiang": "南风",
"fengli": "微风级",
"high": "高温 35℃",
"type": "多云",
"low": "低温 22℃",
"date": "19日星期五"
},
{
"fengxiang": "南风",
"fengli": "3-4级",
"high": "高温 34℃",
"type": "晴",
"low": "低温 21℃",
"date": "20日星期六"
}
],
"yesterday": {
"fl": "微风",
"fx": "南风",
"high": "高温 28℃",
"type": "晴",
"low": "低温 15℃",
"date": "15日星期一"
},
"aqi": "72",
"city": "北京"
}
"""
"""
写入JSON文件
Version: 0.1
Author: 骆昊
Date: 2018-03-13
"""
import json
teacher_dict = {'name': '白元芳', 'age': 25, 'title': '讲师'}
json_str = json.dumps(teacher_dict)
print(json_str)
print(type(json_str))
fruits_list = ['apple', 'orange', 'strawberry', 'banana', 'pitaya']
json_str = json.dumps(fruits_list)
print(json_str)
print(type(json_str))
This diff is collapsed.
骆昊,38,叫兽
狄仁杰,25,砖家
This diff is collapsed.
我如果爱你
绝不学攀援的凌霄花
借你的高枝炫耀自己
我如果爱你
绝不学痴情的鸟儿
为绿荫重复单调的歌曲
"""
字符串常用操作
Version: 0.1
Author: 骆昊
Date: 2018-03-19
"""
import pyperclip
# 转义字符
print('My brother\'s name is \'007\'')
# 原始字符串
print(r'My brother\'s name is \'007\'')
str = 'hello123world'
print('he' in str)
print('her' in str)
# 字符串是否只包含字母
print(str.isalpha())
# 字符串是否只包含字母和数字
print(str.isalnum())
# 字符串是否只包含数字
print(str.isdecimal())
print(str[0:5].isalpha())
print(str[5:8].isdecimal())
list = ['床前明月光', '疑是地上霜', '举头望明月', '低头思故乡']
print('-'.join(list))
sentence = 'You go your way I will go mine'
words_list = sentence.split()
print(words_list)
email = ' jackfrued@126.com '
print(email)
print(email.strip())
print(email.lstrip())
# 将文本放入系统剪切板中
pyperclip.copy('老虎不发猫你当我病危呀')
# 从系统剪切板获得文本
# print(pyperclip.paste())
"""
字符串常用操作 - 实现字符串倒转的方法
Version: 0.1
Author: 骆昊
Date: 2018-03-19
"""
from io import StringIO
def reverse_str1(str):
return str[::-1]
def reverse_str2(str):
if len(str) <= 1:
return str
return reverse_str2(str[1:]) + str[0:1]
def reverse_str3(str):
# StringIO对象是Python中的可变字符串
# 不应该使用不变字符串做字符串连接操作 因为会产生很多无用字符串对象
rstr = StringIO()
str_len = len(str)
for index in range(str_len - 1, -1, -1):
rstr.write(str[index])
return rstr.getvalue()
def reverse_str4(str):
return ''.join(str[index] for index in range(len(str) - 1, -1, -1))
def reverse_str5(str):
# 将字符串处理成列表
str_list = list(str)
str_len = len(str)
# 使用zip函数将两个序列合并成一个产生元组的迭代器
# 每次正好可以取到一前一后两个下标来实现元素的交换
for i, j in zip(range(str_len // 2), range(str_len - 1, str_len // 2, -1)):
str_list[i], str_list[j] = str_list[j], str_list[i]
# 将列表元素连接成字符串
return ''.join(str_list)
if __name__ == '__main__':
str = 'I love Python'
print(reverse_str1(str))
print(str)
print(reverse_str2(str))
print(str)
print(reverse_str3(str))
print(str)
print(reverse_str4(str))
print(str)
print(reverse_str5(str))
print(str)
# 提醒学生注意这是一个面试题: 写出你能想到的实现字符串倒转的代码
"""
验证输入用户名和QQ号是否有效并给出对应的提示信息
要求:
用户名必须由字母、数字或下划线构成且长度在6~20个字符之间
QQ号是5~12的数字且首位不能为0
"""
import re
def main():
username = input('请输入用户名: ')
qq = input('请输入QQ号: ')
m1 = re.match(r'^[0-9a-zA-Z_]{6,20}$', username)
if not m1:
print('请输入有效的用户名.')
m2 = re.match(r'^[1-9]\d{4,11}$', qq)
if not m2:
print('请输入有效的QQ号.')
if m1 and m2:
print('你输入的信息是有效的!')
if __name__ == '__main__':
main()
import re
def main():
# 创建正则表达式对象 使用了前瞻和回顾来保证手机号前后不应该出现数字
pattern = re.compile(r'(?<=\D)(1[38]\d{9}|14[57]\d{8}|15[0-35-9]\d{8}|17[678]\d{8})(?=\D)')
sentence = '''
重要的事情说8130123456789遍,我的手机号是13512346789这个靓号,
不是15600998765,也是110或119,王大锤的手机号才是15600998765。
'''
# 查找所有匹配并保存到一个列表中
mylist = re.findall(pattern, sentence)
print(mylist)
print('--------华丽的分隔线--------')
# 通过迭代器取出匹配对象并获得匹配的内容
for temp in pattern.finditer(sentence):
print(temp.group())
print('--------华丽的分隔线--------')
# 通过search函数指定搜索位置找出所有匹配
m = pattern.search(sentence)
while m:
print(m.group())
m = pattern.search(sentence, m.end())
if __name__ == '__main__':
main()
import re
def main():
sentence = '你丫是傻叉吗? 我操你大爷的. Fuck you.'
purified = re.sub('[操肏艹草曹]|fuck|shit|傻[比屄逼叉缺吊屌]|煞笔',
'*', sentence, flags=re.IGNORECASE)
print(purified)
if __name__ == '__main__':
main()
This diff is collapsed.
"""
异步I/O操作 - asyncio模块
Version: 0.1
Author: 骆昊
Date: 2018-03-21
"""
import asyncio
import threading
# import time
@asyncio.coroutine
def hello():
print('%s: hello, world!' % threading.current_thread())
# 休眠不会阻塞主线程因为使用了异步I/O操作
# 注意有yield from才会等待休眠操作执行完成
yield from asyncio.sleep(2)
# asyncio.sleep(1)
# time.sleep(1)
print('%s: goodbye, world!' % threading.current_thread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
# 等待两个异步I/O操作执行结束
loop.run_until_complete(asyncio.wait(tasks))
print('game over!')
loop.close()
"""
异步I/O操作 - async和await
Version: 0.1
Author: 骆昊
Date: 2018-03-21
"""
import asyncio
import threading
# 通过async修饰的函数不再是普通函数而是一个协程
# 注意async和await将在Python 3.7中作为关键字出现
async def hello():
print('%s: hello, world!' % threading.current_thread())
await asyncio.sleep(2)
print('%s: goodbye, world!' % threading.current_thread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
# 等待两个异步I/O操作执行结束
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment