跳过正文

Python

Python Redis
·147 字
连接redis # import redis # 连接redis def connect_redis(host, port, password): # decode_responses: 是否decode数据,否则返回数据为bytes类型, 例如hgetall返回的是dict[bytes, bytes] 而不是dict[str, str] pool = redis.ConnectionPool(host=host, port=port, password=password, decode_responses=True) cli = redis.Redis(connection_pool=pool) try: cli.ping() except: return None return cli def do_something(cli, key): data = cli.get(key) if data is None: print("key not exists") else: print(data) if __name__ == "__main__": host = "127.0.0.1" port = 6379 password = "foobared" cli = connect_redis(host, port, password) if cli is None: print("connect redis failed") else: do_something(cli, "testttttt")
Requests库
·128 字
简单Get请求 # #!/usr/bin/python3 import requests # get返回html文本 def getData(url): result = requests.get(url) print(result.json()) if __name__ == '__main__': url = "https://mock.apifox.cn/m2/2245336-0-default/64492343" getData(url) Post请求 # form表单请求 # #!/usr/bin/python3 import requests # post form表单请求 def postData(url): data = {"key1": "value1", "key2": "value2"} result = requests.post(url, data=data) print(result.json()) if __name__ == '__main__': url = "https://baidu.com" postData(url) json请求 # #!/usr/bin/python3 import requests # post form表单请求 def postJsonData(url): data = {"key1": "value1", "key2": "value2"} result = requests.post(url, json=data) print(result.json()) if __name__ == '__main__': url = "https://baidu.com" postJsonData(url)
Python100天-多进程多线程编程
·357 字
多进程示例 # from multiprocessing import Process from os import getpid from random import randint from time import time, sleep def download_task(filename): print('启动下载进程,进程号[%d].' % getpid()) print('开始下载%s...' % filename) time_to_download = randint(5, 10) sleep(time_to_download) print('%s下载完成! 耗费了%d秒' % (filename, time_to_download)) def main(): start = time() p1 = Process(target=download_task, args=('Python从入门到住院.pdf', )) p1.start() p2 = Process(target=download_task, args=('Peking Hot.avi', )) p2.start() p1.join() p2.join() end = time() print('总共耗费了%.2f秒.' % (end - start)) if __name__ == '__main__': main() 多线程示例 # from time import sleep from threading import Thread, Lock class Account(object): def __init__(self): self._balance = 0 self._lock = Lock() def deposit(self, money): self._lock.acquire() # 加锁,防止多线程操作统一变量导致的问题 try: new_balance = self._balance + money sleep(0.01) # 模拟交易耗时 self._balance = new_balance finally: self._lock.release() # 释放锁 @property def balance(self): return self._balance class AddMoneyThread(Thread): def __init__(self, account, money): super().__init__() self._account = account self._money = money def run(self): self._account.deposit(self._money) def main(): account = Account() threads = [] for _ in range(100): t = AddMoneyThread(account, 1) threads.append(t) t.start() for t in threads: t.join() print('账户余额:', account.balance) if __name__ == '__main__': main()
Python100天 文件操作
·959 字
文件操作模式 # 操作模式 具体含义 r 只读(默认) w 写入,会清空之前的内容,文件不存在则创建新文件 x 写入,如果文件已存在则会产生异常 a 追加,将内容追加到文件末尾,文件不存在则创建新文件 b 二进制模式 t 文本模式(默认) + 更新,既可以读又可以写 打开文件 # def open_file(filename): fp = None try: fp = open(filename, 'r', encoding='utf-8') print(fp.read()) # except FileNotFoundError: # print('无法打开执行文件,', filename) except LookupError: print('指定了未知的编码,', filename) except UnicodeDecodeError: print('读取文件时解码失败') except Exception as e: print(e) finally: if fp: fp.close() # 推荐使用with open形式打开文件 def with_open_file(filename): try: # with open 形式不需要关心文件句柄的关闭 with open(filename, 'r', encoding='utf-8') as fp: # 一次读取全部内容 # print(fp.read()) # 按行读取 # for line in fp: # print(line.strip('\n')) # 将所有内容按行读取到列表中 lines = fp.readlines() print(lines) except FileNotFoundError: print('无法打开执行文件,', filename) except LookupError: print('指定了未知的编码,', filename) except UnicodeDecodeError: print('读取文件时解码失败') except Exception as e: print(e) if __name__ == '__main__': # open_file('./tests.txt') with_open_file('./test.txt') 文件写入操作 # def write_file(filename): try: # with open 形式不需要关心文件句柄的关闭 with open(filename, 'a', encoding='utf-8') as fp: fp.write('test'+'\n') except IOError: print("写入文件失败") except Exception as e: print(e) if __name__ == '__main__': write_file('./test.txt') 读写 JSON 文件 # JSON 与 Python 类型对应关系
Python100天-面向对象编程
·1293 字
面向对象 # 把一组数据结构和处理它们的方法组成对象(object),把相同行为的对象归纳为类(class), 通过类的封装(encapsulation)隐藏内部细节, 通过继承(inheritance)实现类的特化(specialization)和泛化(generalization), 通过多态(polymorphism)实现基于对象类型的动态分派。
Python100天-数据类型
·2137 字
字符串 # 获取字符串长度 # s = 'abc中文' # 三个双引号可以定义多行字符串 s2 = """test test""" # 获取字符串长度,Python默认使用utf-8字符集,单个汉字字符长度为1 print(len(s)) # 5 print(len(s2)) # 9 查找子字符串 # s = 'abc中文' # find()方法返回子字符串位置,不存在则返回-1 print(s.find('中文')) # 3 print(s.find('d')) # -1 # index()方法找不到子字符串时会报异常,尽量不用 print(s.index('中文')) # 3 print(s.index('d')) # 报错 获取子字符串出现次数 # s = 'aabc中文' # count()方法返回子字符串出现次数 print(s.count('a')) # 2 print(s.count('c中文')) # 1 print(s.count('d')) # 0 字符串是否以子字符串开始或结束 # s = 'abc中文' print(s.startswith('a')) # True print(s.endswith('中文')) # True print(s.endswith('c')) # Flase 切片操作 # s = 'abc中文' print(s[3:]) # 中文 print(s[-2:]) # 中文 # [起始索引:结束索引(不包含):步长] print(s[:]) # abc中文 print(s[:3]) # abc print(s[::2]) # ac文 # [::-1]的效果是反转字符串 print(s[::-1]) # 文中cba 字符串拼接 # s1 = 'abc' s2 = '中文' # +操作符拼接字符串 print(s1+s2) # abc中文 字符串去掉头部或尾部子字符串 # s = '**abc中文**' print(s.strip('*')) # abc中文 print(s.lstrip('*')) # abc中文** print(s.rstrip('*')) # **abc中文 字符串大小写转换 # s = 'abc' print(s.upper()) # ABC print(s.upper().lower()) # abc # 字符串转单词首字母大写 s = 'hello world' print(s.title()) # Hello World # 首字母大写 print(s.capitalize()) # Hello world """ 对应有判断字符串是否小写或者大写的方法 isupper(), islower(), istitle() """ 字符串替换 # s = 'abcc中文' print(s.replace('c', 'd')) # abdd中文 # 指定替换几个 print(s.replace('c', 'd', 1)) # abdc中文 判断是不是纯数字字符串 # """ isdigit() True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字 False: 汉字数字 isdecimal() True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字 False: 罗马数字,汉字数字 Error: byte数字(单字节) isnumeric() True: Unicode数字,全角数字(双字节),罗马数字,汉字数字 Error: byte数字(单字节) """ print('123'.isdigit()) # True print('123a'.isdigit()) # False print('123a'.isalnum()) # True 字符串格式化 # """ %号形式 注意后面变量类型和数量要与前面定义一致,否则报错 """ print('1: %d, a: %s' % (1, 'a')) """ format()方法 format()参数数量要与前面定义数量一致 大于前面定义数量也可以,只用前n个定义的参数 """ print('{0} + {1} = {2}'.format(1, 2, 3)) """ f'{var}'形式(Python3.6以后版本) """ a, b = 1, 2 print(f'{a} + {b} = {a+b}') 字符串填充 # s = '标题' print(s.center(20, '-')) # ---------标题--------- print(s.ljust(20, '-')) # 标题------------------ print(s.rjust(20, '-')) # ------------------标题 列表 # 获取列表长度 # l = [1,2,'a'] print(len(l)) # 3 索引操作 # l = [1,2,3] print(l[0]) # 1 print(l[-1]) # 3 遍历列表 # l = ['a', 'b', 'c'] # 通过循环用下标遍历列表元素 for i in range(len(l)): print(l[i]) # 通过for循环遍历列表元素 for item in l: print(item) # 通过enumerate函数处理列表之后再遍历可以同时获得元素索引和值 for i, item in enumerate(l): print(i, item) 列表添加删除元素 # l = [1,2,3] # 添加元素 # insert(index, item) l.insert(0, 0) # [0, 1, 2, 3] l.append(4) # [0, 1, 2, 3, 4] # 合并列表 l.extend([5, 6]) # [0, 1, 2, 3, 4, 5, 6] l += [7, 8] # [0, 1, 2, 3, 4, 5, 6, 7, 8] # 删除元素 # 直接删除元素, 如果有多个重复的元素,remove()只删除第一个 if 1 in l: l.remove(1) # 根据索引删除 item = l.pop(0) print(item) # 清空元素 l.clear() 切片操作 # l1 = [1,2,3] l2 = l1 # 浅拷贝 l3 = l1[:] # 切片操作后的修改不会影响原列表 l2[0] = 4 l2.append(5) l3[0] = 5 print(l1) # [4, 2, 3, 5] print(l2) # [4, 2, 3, 5] print(l3) # [5, 2, 3] la = ['a', 'b', 'c'] lb = la[:2] # ['a', 'b'] lb = la[::2] # ['a', 'c'] lc = la[::-1] # ['c', 'b', 'a'], 反转列表 列表排序 # l = ['a', 'd', 'c', 'ef'] # 列表对象sort()方法,直接修改列表对象 l.sort() print(l) # ['a', 'c', 'd', 'ef'] l.sort(reverse=True) print(l) # ['ef', 'd', 'c', 'a'] # sorted()方法 l2 = sorted(l) print(l2) # ['a', 'c', 'd', 'ef'] l3 = sorted(l2, reverse=True) print(l3) # ['ef', 'd', 'c', 'a'] l4 = sorted(l2, key=len) print(l4) # ['a', 'c', 'd', 'ef'] 生成式和生成器 # # 生成式,相比生成器占用更多内存空间 f = [x for x in range(1, 5)] # f是列表对象 print(f) # [1, 2, 3, 4] f = [x + y for x in 'ABC' for y in '123'] print(f) # ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'] f = (x for x in range(1, 5)) # f是生成器对象 for v in f: print(v) 元组 # 元组元素不可修改, 元组和字符串一样属于不可变类型