python笔记
一、常用函数
1.Url检测
def check_url(_u):
regex = re.compile(
r'^(?:http|ftp)s?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|'
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
r'(?::\d+)?'
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
return regex.match(_u)
2. 实时获得控制台输出
import subprocess
import locale
import codecs
def get_stdout(RUN_CMD):
ps = subprocess.Popen(RUN_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=False)
while True:
data = ps.stdout.readline()
if data == b'':
if ps.poll() is not None:
break
else:
print(data.decode(codecs.lookup(locale.getpreferredencoding()).name))
二. 飘逸的语法
1. python带参数的装饰器
def print_line(char='-'):
"""
功能: 根据参数生成不同的装饰器
:param char: 显示分割线的字符
:return:返回一个装饰器
"""
def char_decorator(func):
"""
功能: 一个装饰器,给函数打印一个分割线
:param func:需要执行的参数
:return:返回对应的执行函数
"""
print(char * 15, 'function:', func.__name__, char * 15)
return lambda *args, **kwargs: func(*args, **kwargs)
return char_decorator
@print_line('-')
def line(print_text):
return print_text
if __name__ == '__main__':
print(line('请帮我把这段话返回出来'))
2. 求两个集合之间的交并差集
l1 = [i for i in range(0, 10, 2)]
l2 = [i for i in range(1, 10, 2)]
l3 = [i for i in range(1, 10)]
print(l1, l2, l3)
print(set(l1).union(set(l2)))
print(set(l1) | set(l2))
print(set(l1).intersection(set(l3)))
print(set(l1) & set(l3))
print(set(l1).difference(set(l3)))
print(set(l1) - set(l3))
print(set(l3).difference(set(l1)))
print(set(l3) - set(l1))
3. python生成器的简单使用
gen = (num for num in range(10000) if not num % 2)
def gen_func(_n):
"""
功能: 生成一个包含数值0-_n的生成器
:param _n:指定执行范围
:return:返回一个生成器
"""
for num in range(_n):
yield num
if __name__ == '__main__':
for num in gen:
print(num)
for num in gen_func(10):
print(num)
help(gen_func)