Python3高阶教程

    1. Python3正则表达式 (预计时间: 30min)
      正则表达式是强大的文本处理工具,用于匹配、搜索和替换字符串中的特定模式。
    • 1.1 正则表达式基础
      import re
      
      # 基本匹配
      pattern = r'hello'
      text = 'hello world'
      
      match = re.search(pattern, text)
      if match:
      	print(f"找到匹配: {match.group()}")  # 输出: 找到匹配: hello
      
      # 常用元字符
      # . 匹配任意字符(除换行符)
      # \d 匹配数字 \w 匹配字母数字或下划线 \s 匹配空白字符
      # ^ 匹配开头 $ 匹配结尾
      # * 0次或多次 + 1次或多次 ? 0次或1次 {n,m} n到m次
      
    • 1.2 实际应用示例
      import re
      
      # 邮箱验证
      def validate_email(email):
      	pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$'
      	return bool(re.match(pattern, email))
      print(validate_email('test@example.com'))  # True
      print(validate_email('invalid-email'))     # False
      
      # 手机号提取
      text = "联系电话: 138-1234-5678, 另一个: 150-9876-5432"
      phone_pattern = r'\d{3}-\d{4}-\d{4}'
      phones = re.findall(phone_pattern, text)
      print(f"提取的手机号: {phones}")  # ['138-1234-5678', '150-9876-5432']
      
      # 文本替换
      text = "今天是2024-08-23,明天是2024-08-24"
      new_text = re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\1年\2月\3日', text)
      print(new_text)  # 今天是2024年08月23日,明天是2024年08月24日
      
    1. Python数据库连接驱动之MySQL (预计时间: 20min)
      使用PyMySQL连接和操作MySQL数据库。
    • 2.1 数据库连接与基本操作
      import pymysql
      from datetime import datetime
      
      class MySQLManager:
      	def init(self, host='localhost', user='root', password='password', database='testdb'):
      		self.connection = pymysql.connect(
      										host=host,
      										user=user,
      										password=password,
      										database=database,
      										charset='utf8mb4',
      										cursorclass=pymysql.cursors.DictCursor
      										)
      
      	def create_table(self):
      	    """创建用户表"""
      	    with self.connection.cursor() as cursor:
      	        sql = """
      	        CREATE TABLE IF NOT EXISTS users (
      	            id INT AUTO_INCREMENT PRIMARY KEY,
      	            name VARCHAR(100) NOT NULL,
      	            email VARCHAR(100) UNIQUE NOT NULL,
      	            age INT,
      	            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      	        )
      	        """
      	        cursor.execute(sql)
      	    self.connection.commit()
      	
      	def insert_user(self, name, email, age):
      	    """插入用户数据"""
      	    try:
      	        with self.connection.cursor() as cursor:
      	            sql = "INSERT INTO users (name, email, age) VALUES (%s, %s, %s)"
      	            cursor.execute(sql, (name, email, age))
      	        self.connection.commit()
      	        return True
      	    except pymysql.Error as e:
      	        print(f"插入错误: {e}")
      	        return False
      	
      	def get_users(self):
      	    """查询所有用户"""
      	    with self.connection.cursor() as cursor:
      	        sql = "SELECT * FROM users"
      	        cursor.execute(sql)
      	        return cursor.fetchall()
      	
      	def close(self):
      	    """关闭连接"""
      	    self.connection.close()
      
      # 使用示例
      db = MySQLManager()
      db.create_table()
      db.insert_user("张三", "zhangsan@example.com", 25)
      db.insert_user("李四", "lisi@example.com", 30)
      
      users = db.get_users()
      for user in users:
      	print(user)
      db.close()
      
    1. Python数据库连接驱动之Sql Server (预计时间: 10min)
      使用pymssql连接SQL Server数据库。
      import pymssql
      
      class SQLServerManager:
      	def init(self, server='localhost', user='sa', password='password', database='testdb'):
      		self.connection = pymssql.connect(
      										server=server,
      										user=user,
      										password=password,
      										database=database
      										)
      	
      	def execute_query(self, query, params=None):
      	    """执行查询"""
      	    with self.connection.cursor() as cursor:
      	        cursor.execute(query, params)
      	        return cursor.fetchall()
      	
      	def execute_non_query(self, query, params=None):
      	    """执行非查询语句"""
      	    try:
      	        with self.connection.cursor() as cursor:
      	            cursor.execute(query, params)
      	        self.connection.commit()
      	        return True
      	    except Exception as e:
      	        print(f"执行错误: {e}")
      	        self.connection.rollback()
      	        return False
              
      # 使用示例
      server = SQLServerManager()
      result = server.execute_query("SELECT * FROM Products")
      
    1. Python3邮件发送之SMTP (预计时间: 30min)
      使用smtplib和email库发送邮件。
      import smtplib
      from email.mime.text import MimeText
      from email.mime.multipart import MimeMultipart
      from email.header import Header
      
      class EmailSender:
      	def init(self, smtp_server, port, username, password):
      		self.smtp_server = smtp_server
      		self.port = port
      		self.username = username
      		self.password = password
      
      	def send_text_email(self, to_addr, subject, content):
      	    """发送文本邮件"""
      	    # 创建邮件对象
      	    msg = MimeMultipart()
      	    msg['From'] = self.username
      	    msg['To'] = to_addr
      	    msg['Subject'] = Header(subject, 'utf-8')
      	    
      	    # 邮件正文
      	    msg.attach(MimeText(content, 'plain', 'utf-8'))
      	    
      	    try:
      	        # 连接服务器并发送
      	        server = smtplib.SMTP(self.smtp_server, self.port)
      	        server.starttls()  # 启用安全连接
      	        server.login(self.username, self.password)
      	        server.send_message(msg)
      	        server.quit()
      	        print("邮件发送成功!")
      	        return True
      	    except Exception as e:
      	        print(f"邮件发送失败: {e}")
      	        return False
      	
      	def send_html_email(self, to_addr, subject, html_content):
      	    """发送HTML邮件"""
      	    msg = MimeMultipart()
      	    msg['From'] = self.username
      	    msg['To'] = to_addr
      	    msg['Subject'] = Header(subject, 'utf-8')
      	    
      	    # HTML正文
      	    msg.attach(MimeText(html_content, 'html', 'utf-8'))
      	    
      	    # 发送逻辑同上
      	    # ...
      	    
      # 使用示例
      sender = EmailSender(
      					smtp_server='smtp.163.com',
      					port=587,
      					username='your_email@163.com',
      					password='your_password'
      					)
      
      # 发送文本邮件
      sender.send_text_email(
      					to_addr='recipient@example.com',
      					subject='测试邮件',
      					content='这是一封测试邮件内容。'
      					)
      
      # 发送HTML邮件
      html_content = '''
      				<h1>HTML邮件测试</h1>
      				<p>这是一封<strong>HTML格式</strong>的邮件。</p>
      				<ul>
      				<li>项目一</li>
      				<li>项目二</li>
      				</ul>
      				'''
      
      sender.send_html_email(
      					to_addr='recipient@example.com',
      					subject='HTML测试邮件',
      					content=html_content
      					)
      
    1. Python3多线程 (预计时间: 10min)
      使用threading模块实现多线程编程。
      import threading
      import time
      from queue import Queue
      
      class ThreadExample:
      	def init(self):
      		self.lock = threading.Lock()
      		self.results = []
      
      	def worker(self, task_id, delay):
      	    """工作线程函数"""
      	    print(f"线程 {task_id} 开始执行,延迟 {delay} 秒")
      	    time.sleep(delay)
      	    
      	    # 使用锁确保线程安全
      	    with self.lock:
      	        self.results.append(f"任务 {task_id} 完成")
      	    
      	    print(f"线程 {task_id} 执行完成")
      	
      	def run_threads(self, num_threads=3):
      	    """运行多线程示例"""
      	    threads = []
      	    
      	    for i in range(num_threads):
      	        # 创建线程,每个线程延迟时间不同
      	        thread = threading.Thread(
      	            target=self.worker, 
      	            args=(i, i + 1)
      	        )
      	        threads.append(thread)
      	        thread.start()
      	    
      	    # 等待所有线程完成
      	    for thread in threads:
      	        thread.join()
      	 
      	    print("所有线程执行完成!")
      	    print(f"结果: {self.results}")
      
      # 使用线程池
      from concurrent.futures import ThreadPoolExecutor
      def parallel_processing(data_list):
      	"""使用线程池进行并行处理"""
      	def process_item(item):
      		# 模拟处理过程
      		time.sleep(1)
      		return item * 2
      		with ThreadPoolExecutor(max_workers=3) as executor:
      		    results = list(executor.map(process_item, data_list))
      		return results
      
      # 使用示例
      example = ThreadExample()
      example.run_threads(3)
      
      # 线程池示例
      data = [1, 2, 3, 4, 5]
      results = parallel_processing(data)
      print(f"并行处理结果: {results}")
      
    1. Python3数据解析之XML (预计时间: 10min)
      使用xml.etree.ElementTree解析XML数据。
      import xml.etree.ElementTree as ET
      
      # XML字符串示例
      xml_data = '''
      			<library>
      			<book id="1">
      			<title>Python编程入门</title>
      			<author>张三</author>
      			<price>59.90</price>
      			<category>编程</category>
      			</book>
      			<book id="2">
      			<title>数据结构与算法</title>
      			<author>李四</author>
      			<price>79.90</price>
      			<category>计算机科学</category>
      			</book>
      			</library>
      			'''
      
      class XMLParser:
      	def parse_books(self, xml_string):
      		"""解析图书XML"""
      		root = ET.fromstring(xml_string)
      		books = []
      		for book_elem in root.findall('book'):
      		    book = {
      		        'id': book_elem.get('id'),
      		        'title': book_elem.find('title').text,
      		        'author': book_elem.find('author').text,
      		        'price': float(book_elem.find('price').text),
      		        'category': book_elem.find('category').text
      		    }
      		    books.append(book)
      		return books
      	
      	def create_books_xml(self, books_data):
      		"""创建图书XML"""
      		library = ET.Element('library')
      		for book_data in books_data:
      		    book = ET.SubElement(library, 'book')
      		    book.set('id', str(book_data['id']))
      		    ET.SubElement(book, 'title').text = book_data['title']
      		    ET.SubElement(book, 'author').text = book_data['author']
      		    ET.SubElement(book, 'price').text = str(book_data['price'])
      		    ET.SubElement(book, 'category').text = book_data['category']
      		return ET.tostring(library, encoding='unicode')
      
      # 使用示例
      parser = XMLParser()
      books = parser.parse_books(xml_data)
      for book in books:
      	print(f"书名: {book['title']}, 作者: {book['author']}, 价格: {book['price']}")
      
      # 创建XML
      new_books = [{'id': 3, 'title': '新书', 'author': '王五', 'price': 45.0, 'category': '文学'}]
      new_xml = parser.create_books_xml(new_books)
      print("生成的XML:")
      print(new_xml)
      
    1. Python3数据解析之JSON (预计时间: 10min)
      JSON是现代应用中最常用的数据交换格式。
      import json
      from datetime import datetime
      
      class JSONHandler:
      	def init(self):
      		self.data = {
      			"users": [
      				{
      				"id": 1,
      				"name": "张三",
      				"email": "zhangsan@example.com",
      				"is_active": True,
      				"created_at": "2024-08-23T10:00:00"
      				},
      				{
      				"id": 2,
      				"name": "李四",
      				"email": "lisi@example.com",
      				"is_active": False,
      				"created_at": "2024-08-22T15:30:00"
      				}
      			],
      			"total_count": 2
      		}
      	
      	def save_to_file(self, filename):
      	    """保存到JSON文件"""
      	    with open(filename, 'w', encoding='utf-8') as f:
      	        json.dump(self.data, f, ensure_ascii=False, indent=2)
      	    print(f"数据已保存到 {filename}")
      	
      	def load_from_file(self, filename):
      	    """从JSON文件加载"""
      	    try:
      	        with open(filename, 'r', encoding='utf-8') as f:
      	            loaded_data = json.load(f)
      	        self.data = loaded_data
      	        print(f"数据已从 {filename} 加载")
      	        return True
      	    except FileNotFoundError:
      	        print("文件不存在")
      	        return False
      	
      	def pretty_print(self):
      	    """格式化输出JSON"""
      	    print(json.dumps(self.data, ensure_ascii=False, indent=2))
      	
      	def add_user(self, user_data):
      	    """添加用户"""
      	    self.data["users"].append(user_data)
      	    self.data["total_count"] = len(self.data["users"])
      	
      	def find_user_by_id(self, user_id):
      	    """根据ID查找用户"""
      	    for user in self.data["users"]:
      	        if user["id"] == user_id:
      	            return user
      	    return None
      	    
      # 使用示例
      handler = JSONHandler()
      
      # 添加新用户
      new_user = {
      			"id": 3,
      			"name": "王五",
      			"email": "wangwu@example.com",
      			"is_active": True,
      			"created_at": datetime.now().isoformat()
      			}
      handler.add_user(new_user)
      
      # 查找用户
      user = handler.find_user_by_id(1)
      print(f"找到用户: {user}")
      
      # 保存和加载
      handler.save_to_file("users.json")
      handler.pretty_print()
      
    1. Python3日期和时间处理 (预计时间: 10min)
      使用datetime模块处理日期和时间。
      from datetime import datetime, date, time, timedelta
      import time as time_module
      
      class DateTimeExamples:
      	def basic_operations(self):
      		"""基本日期时间操作"""
      		# 当前日期时间
      		now = datetime.now()
      		print(f"当前时间: {now}")
      		print(f"日期: {now.date()}")
      		print(f"时间: {now.time()}")
      		
      		# 特定日期
      		some_date = date(2024, 8, 23)
      		some_time = time(14, 30, 45)
      		some_datetime = datetime(2024, 8, 23, 14, 30, 45)
      		
      		print(f"特定日期: {some_date}")
      		print(f"特定时间: {some_time}")
      		print(f"特定日期时间: {some_datetime}")
      
      	def arithmetic_operations(self):
      		"""日期时间运算"""
      		today = datetime.now()
      		# 加减时间
      		tomorrow = today + timedelta(days=1)
      		last_week = today - timedelta(weeks=1)
      		next_hour = today + timedelta(hours=1)
      		print(f"今天: {today}")
      		print(f"明天: {tomorrow}")
      		print(f"上周: {last_week}")
      		print(f"一小时后: {next_hour}")
      	
      		# 计算时间差
      		date1 = datetime(2024, 1, 1)
      		date2 = datetime(2024, 8, 23)
      		difference = date2 - date1
      		print(f"天数差: {difference.days} 天")
      	
      	def formatting(self):
      		"""日期时间格式化"""
      		now = datetime.now()
      		
      		# 转换为字符串
      		iso_format = now.isoformat()
      		custom_format = now.strftime("%Y年%m月%d日 %H时%M分%S秒")
      		date_only = now.strftime("%Y-%m-%d")
      		time_only = now.strftime("%H:%M:%S")
      		
      		print(f"ISO格式: {iso_format}")
      		print(f"自定义格式: {custom_format}")
      		print(f"仅日期: {date_only}")
      		print(f"仅时间: {time_only}")
      	
      		# 字符串转换为日期时间
      		date_str = "2024-08-23 14:30:00"
      		parsed_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
      		print(f"解析后的日期: {parsed_date}")
      	
      	def timezones_example(self):
      		"""时区处理(需要pytz库)"""
      		# 安装: pip install pytz
      		try:
      		    import pytz
      		    # 本地时间
      		    local_time = datetime.now()
      		    print(f"本地时间: {local_time}")
      		    
      		    # UTC时间
      		    utc_time = datetime.now(pytz.utc)
      		    print(f"UTC时间: {utc_time}")
      		    
      		    # 特定时区
      		    beijing_tz = pytz.timezone('Asia/Shanghai')
      		    beijing_time = datetime.now(beijing_tz)
      		    print(f"北京时间: {beijing_time}")
      		    
      		except ImportError:
      		    print("请安装pytz库: pip install pytz")
      	    
      # 使用示例
      dt_example = DateTimeExamples()
      dt_example.basic_operations()
      print("\n" + "="*50)
      
      dt_example.arithmetic_operations()
      print("\n" + "="*50)
      
      dt_example.formatting()
      
    1. Python3内置函数 (预计时间: 10min)
      Python提供了丰富的内置函数,无需导入即可使用。
      class BuiltInFunctions:
      	def demonstrate_functions(self):
      		"""演示常用内置函数"""
      		# 数学相关
      		numbers = [1, 2, 3, 4, 5]
      		print(f"列表: {numbers}")
      		print(f"长度: {len(numbers)}")
      		print(f"总和: {sum(numbers)}")
      		print(f"最大值: {max(numbers)}")
      		print(f"最小值: {min(numbers)}")
      		print(f"绝对值: {abs(-10)}")
      		print(f"四舍五入: {round(3.14159, 2)}")
      		
      		# 类型转换
      		print(f"整数转换: {int('123')}")
      		print(f"浮点数转换: {float('3.14')}")
      		print(f"字符串转换: {str(123)}")
      		print(f"列表转换: {list('hello')}")
      		print(f"元组转换: {tuple([1, 2, 3])}")
      		print(f"字典转换: {dict([('a', 1), ('b', 2)])}")
      		
      		# 迭代相关
      		names = ['Alice', 'Bob', 'Charlie']
      		print(f"枚举: {list(enumerate(names))}")
      		print(f"Zip: {list(zip([1, 2, 3], names))}")
      		
      		# 布尔判断
      		print(f"全部为真: {all([True, 1, 'hello'])}")
      		print(f"任意为真: {any([False, 0, ''])}")
      		
      		# 其他重要函数
      		print(f"范围: {list(range(5))}")
      		print(f"排序: {sorted([3, 1, 4, 1, 5])}")
      		print(f"反转: {list(reversed([1, 2, 3]))}")
      
      	def advanced_functions(self):
      		"""高级内置函数"""
      		# map函数:对每个元素应用函数
      		numbers = [1, 2, 3, 4, 5]
      		squared = list(map(lambda x: x**2, numbers))
      		print(f"平方: {squared}")
      		# filter函数:过滤元素
      		evens = list(filter(lambda x: x % 2 == 0, numbers))
      		print(f"偶数: {evens}")
      		
      		# reduce函数:累积计算
      		from functools import reduce
      		product = reduce(lambda x, y: x * y, numbers)
      		print(f"乘积: {product}")
      		
      		# zip函数:并行迭代
      		names = ['Alice', 'Bob', 'Charlie']
      		scores = [85, 92, 78]
      		for name, score in zip(names, scores):
      		    print(f"{name}: {score}分")
      		
      		# 列表推导式(虽然不是函数,但很重要)
      		squares = [x**2 for x in numbers if x > 2]
      		print(f"条件平方: {squares}")
      	
      # 使用示例
      built_ins = BuiltInFunctions()
      built_ins.demonstrate_functions()
      print("\n" + "="*50)
      
      built_ins.advanced_functions()
      
    1. Python3模块安装工具之pip (预计时间: 10min)
      pip是Python的包管理工具,用于安装和管理第三方库。
      # pip常用命令示例(在命令行中执行,非Python代码)
      """
      安装包
      pip install package_name
      pip install requests pandas numpy
      
      安装特定版本
      pip install django==3.2.0
      
      升级包
      pip install --upgrade package_name
      
      卸载包
      pip uninstall package_name
      
      查看已安装的包
      pip list
      
      查看包详情
      pip show package_name
      
      生成requirements.txt
      pip freeze > requirements.txt
      
      从requirements.txt安装
      pip install -r requirements.txt
      
      使用国内镜像加速
      pip install -i https://pypi.tuna.tsinghua.edu.cn/simplepackage_name
      """
      
      class PipHelper:
      	"""辅助检查pip环境的类"""
      
      	@staticmethod
      	def check_installed(package_name):
      	    """检查包是否已安装"""
      	    try:
      	        __import__(package_name)
      	        return True
      	    except ImportError:
      	        return False
      	
      	@staticmethod
      	def get_installed_packages():
      	    """获取已安装的包(需要pip模块)"""
      	    try:
      	        import pip
      	        installed_packages = [package.key for package in pip.get_installed_distributions()]
      	        return installed_packages
      	    except:
      	        return "无法获取包列表,请确保pip可用"
      	
      	def create_requirements_file(self, filename='requirements.txt'):
      	    """创建requirements文件模板"""
      	    requirements = [
      	        "requests>=2.25.0",
      	        "pandas>=1.3.0", 
      	        "numpy>=1.21.0",
      	        "django>=3.2.0",
      	        "flask>=2.0.0"
      	    ]
      	    
      	    with open(filename, 'w') as f:
      	        for req in requirements:
      	            f.write(req + '\n')
      	    
      	    print(f"已创建 {filename} 文件")
      	    
      # 使用示例
      helper = PipHelper()
      print(f"requests已安装: {helper.check_installed('requests')}")
      print(f"已安装的包: {helper.get_installed_packages()[:5]}...")  # 显示前5个
      
      helper.create_requirements_file()
      
    1. Python3模块之urllib (预计时间: 30min)
      urllib是Python内置的HTTP请求库。
      from urllib import request, parse, error
      import json
      
      class UrllibExamples:
      	def simple_get(self, url):
      		"""简单的GET请求"""
      		try:
      			with request.urlopen(url) as response:
      			content = response.read().decode('utf-8')
      			print(f"状态码: {response.getcode()}")
      			print(f"内容长度: {len(content)} 字符")
      			return content
      		except error.URLError as e:
      			print(f"请求错误: {e}")
      		return None
      
      	def get_with_headers(self, url):
      	    """带请求头的GET请求"""
      	    req = request.Request(url)
      	    req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
      	    req.add_header('Accept', 'application/json')
      	    try:
      	        with request.urlopen(req) as response:
      	            return response.read().decode('utf-8')
      	    except error.HTTPError as e:
      	        print(f"HTTP错误: {e.code} {e.reason}")
      	        return None
      	
      	def post_request(self, url, data_dict):
      	    """POST请求"""
      	    data = parse.urlencode(data_dict).encode('utf-8')
      	    req = request.Request(url, data=data)
      	    req.add_header('Content-Type', 'application/x-www-form-urlencoded')
      	    try:
      	        with request.urlopen(req) as response:
      	            return response.read().decode('utf-8')
      	    except error.HTTPError as e:
      	        print(f"POST错误: {e}")
      	        return None
      	
      	def download_file(self, url, filename):
      	    """下载文件"""
      	    try:
      	        request.urlretrieve(url, filename)
      	        print(f"文件已下载: {filename}")
      	        return True
      	    except error.URLError as e:
      	        print(f"下载错误: {e}")
      	        return False
      	
      	def parse_url_example(self):
      	    """URL解析示例"""
      	    url = "https://example.com:8080/path/to/page?name=value&id=123#section"
      	    parsed = parse.urlparse(url)
      	    print(f"协议: {parsed.scheme}")
      	    print(f"网络地址: {parsed.netloc}")
      	    print(f"路径: {parsed.path}")
      	    print(f"查询参数: {parsed.query}")
      	    print(f"片段: {parsed.fragment}")
      	    
      	    # 解析查询参数
      	    params = parse.parse_qs(parsed.query)
      	    print(f"参数字典: {params}")
      	    
      # 使用示例
      urllib_example = UrllibExamples()
      # GET请求
      content = urllib_example.simple_get('https://httpbin.org/json')
      if content:
      	print("GET请求成功")
      
      # POST请求
      data = {'key1': 'value1', 'key2': 'value2'}
      response = urllib_example.post_request('https://httpbin.org/post', data)
      if response:
      	print("POST请求成功")
      
      # URL解析
      urllib_example.parse_url_example()
      
    1. Python3模块之operator (预计时间: 10min)
      operator模块提供函数式接口替代运算符。
      import operator
      from functools import reduce
      
      class OperatorDemo:
      	def arithmetic_operations(self):
      		"""算术运算"""
      		a, b = 10, 3
      		print(f"{a} + {b} = {operator.add(a, b)}")
      		print(f"{a} - {b} = {operator.sub(a, b)}")
      		print(f"{a} * {b} = {operator.mul(a, b)}")
      		print(f"{a} / {b} = {operator.truediv(a, b)}")
      		print(f"{a} // {b} = {operator.floordiv(a, b)}")
      		print(f"{a} % {b} = {operator.mod(a, b)}")
      		print(f"{a} ** {b} = {operator.pow(a, b)}")
      
      	def comparison_operations(self):
      		"""比较运算"""
      		values = [5, 10, 5, 15]
      		print(f"5 == 10: {operator.eq(5, 10)}")
      		print(f"5 != 10: {operator.ne(5, 10)}")
      		print(f"5 < 10: {operator.lt(5, 10)}")
      		print(f"5 <= 10: {operator.le(5, 10)}")
      		print(f"10 > 5: {operator.gt(10, 5)}")
      		print(f"10 >= 5: {operator.ge(10, 5)}")
      	
      		# 用于排序
      		data = [(1, 'z'), (3, 'a'), (2, 'm')]
      		sorted_by_first = sorted(data, key=operator.itemgetter(0))
      		sorted_by_second = sorted(data, key=operator.itemgetter(1))
      		
      		print(f"按第一个元素排序: {sorted_by_first}")
      		print(f"按第二个元素排序: {sorted_by_second}")
      		
      	def item_access(self):
      		"""项访问操作"""
      		data = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}
      		
      		# 获取字典值
      		get_name = operator.itemgetter('name')
      		print(f"姓名: {get_name(data)}")
      		
      		# 获取多个值
      		get_info = operator.itemgetter('name', 'age')
      		print(f"信息: {get_info(data)}")
      
      # 属性获取
      class Person:
          def __init__(self, name, age):
              self.name = name
              self.age = age
              
      person = Person('Bob', 30)
      get_age = operator.attrgetter('age')
      print(f"年龄: {get_age(person)}")
      
      def functional_usage(self):
      	"""函数式编程用法"""
      	numbers = [1, 2, 3, 4, 5]
      	# 使用operator替代lambda
      	sum_squares = reduce(operator.add, map(operator.pow, numbers, [2]*len(numbers)))
      	print(f"平方和: {sum_squares}")
      	
      	# 条件过滤
      	greater_than_3 = list(filter(lambda x: operator.gt(x, 3), numbers))
      	print(f"大于3的数: {greater_than_3}")
      
      # 使用示例
      op_demo = OperatorDemo()
      op_demo.arithmetic_operations()
      print("\n" + "="*50)
      
      op_demo.comparison_operations()
      print("\n" + "="*50)
      op_demo.item_access()
      
    1. Python3模块之math (预计时间: 10min)
      math模块提供数学运算函数。
      import math
      
      class MathExamples:
      	def basic_operations(self):
      		"""基本数学运算"""
      		print(f"π = {math.pi}")
      		print(f"e = {math.e}")
      		print(f"平方根 √25 = {math.sqrt(25)}")
      		print(f"幂运算 2³ = {math.pow(2, 3)}")
      		print(f"指数 e² = {math.exp(2)}")
      		print(f"自然对数 ln(10) = {math.log(10)}")
      		print(f"常用对数 log₁₀(100) = {math.log10(100)}")
      	
      	def trigonometric_functions(self):
      	    """三角函数"""
      	    angle_deg = 45
      	    angle_rad = math.radians(angle_deg)
      	    
      	    print(f"{angle_deg}° = {angle_rad:.4f} 弧度")
      	    print(f"sin({angle_deg}°) = {math.sin(angle_rad):.4f}")
      	    print(f"cos({angle_deg}°) = {math.cos(angle_rad):.4f}")
      	    print(f"tan({angle_deg}°) = {math.tan(angle_rad):.4f}")
      	    
      	    # 反三角函数
      	    value = 0.5
      	    print(f"arcsin({value}) = {math.degrees(math.asin(value)):.2f}°")
      	    print(f"arccos({value}) = {math.degrees(math.acos(value)):.2f}°")
      	    print(f"arctan({value}) = {math.degrees(math.atan(value)):.2f}°")
      	
      	def special_functions(self):
      	    """特殊函数"""
      	    print(f"阶乘 5! = {math.factorial(5)}")
      	    print(f"最大公约数 gcd(12, 18) = {math.gcd(12, 18)}")
      	    print(f"组合数 C(5,2) = {math.comb(5, 2)}")
      	    print(f"排列数 P(5,2) = {math.perm(5, 2)}")
      	    
      	    # 双曲函数
      	    x = 1.0
      	    print(f"sinh({x}) = {math.sinh(x):.4f}")
      	    print(f"cosh({x}) = {math.cosh(x):.4f}")
      	    print(f"tanh({x}) = {math.tanh(x):.4f}")
      	
      	def practical_examples(self):
      	    """实际应用示例"""
      	    # 计算圆的面积和周长
      	    radius = 5
      	    area = math.pi * math.pow(radius, 2)
      	    circumference = 2 * math.pi * radius
      	    print(f"半径 {radius} 的圆: 面积={area:.2f}, 周长={circumference:.2f}")
      	    
      	    # 计算两点间距离
      	    point1 = (1, 2)
      	    point2 = (4, 6)
      	    distance = math.dist(point1, point2)
      	    print(f"点{point1}到点{point2}的距离: {distance:.2f}")
      	    
      	    # 角度转换
      	    degrees = 180
      	    radians = math.radians(degrees)
      	    print(f"{degrees}° = {radians:.4f} 弧度")
      
      # 使用示例
      math_example = MathExamples()
      math_example.basic_operations()
      print("\n" + "="*50)
      
      math_example.trigonometric_functions()
      print("\n" + "="*50)
      
      math_example.special_functions()
      print("\n" + "="*50)
      
      math_example.practical_examples()
      
    1. Python3模块之requests (预计时间: 10min)
      requests是更简洁易用的HTTP库。
      import requests
      import json
      
      class RequestsExamples:
      	def init(self):
      		self.session = requests.Session()
      		# 设置通用请求头
      		self.session.headers.update({
      		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      		'Accept': 'application/json'
      		})
      
      	def get_request(self, url, params=None):
      	    """GET请求"""
      	    try:
      	        response = self.session.get(url, params=params, timeout=10)
      	        response.raise_for_status()  # 如果状态码不是200,抛出异常
      	        return response
      	    except requests.exceptions.RequestException as e:
      	        print(f"请求错误: {e}")
      	        return None
      	
      	def post_request(self, url, data=None, json_data=None):
      	    """POST请求"""
      	    try:
      	        response = self.session.post(url, data=data, json=json_data, timeout=10)
      	        response.raise_for_status()
      	        return response
      	    except requests.exceptions.RequestException as e:
      	        print(f"POST错误: {e}")
      	        return None
      	
      	def download_file(self, url, filename):
      	    """下载文件"""
      	    try:
      	        response = self.session.get(url, stream=True, timeout=30)
      	        response.raise_for_status()
      	        
      	        with open(filename, 'wb') as f:
      	            for chunk in response.iter_content(chunk_size=8192):
      	                f.write(chunk)
      	        print(f"文件已下载: {filename}")
      	        return True
      	    except requests.exceptions.RequestException as e:
      	        print(f"下载错误: {e}")
      	        return False
      	
      	def api_example(self):
      	    """API调用示例"""
      	    # 获取公开API数据
      	    response = self.get_request('https://api.github.com/users/octocat')
      	    if response:
      	        user_data = response.json()
      	        print(f"用户名: {user_data.get('login')}")
      	        print(f"姓名: {user_data.get('name')}")
      	        print(f"仓库数: {user_data.get('public_repos')}")
      	    
      	    # 发送JSON数据
      	    json_data = {
      	        'title': '测试标题',
      	        'body': '测试内容',
      	        'userId': 1
      	    }
      	    
      	    response = self.post_request(
      	        'https://jsonplaceholder.typicode.com/posts',
      	        json_data=json_data
      	    )
      	    
      	    if response:
      	        result = response.json()
      	        print(f"创建的文章ID: {result.get('id')}")
              
      # 使用示例
      req_example = RequestsExamples()
      
      # GET请求示例
      response = req_example.get_request('https://httpbin.org/json')
      
      if response:
      	print(f"状态码: {response.status_code}")
      	print(f"内容类型: {response.headers.get('content-type')}")
      	data = response.json()
      	print(f"API响应: {data.get('slideshow', {}).get('title')}")
      
      # API示例
      req_example.api_example()
      
    1. Python3模块之random (预计时间: 10min)
      random模块用于生成随机数。
      import random
      import string
      
      class RandomExamples:
      	def basic_random(self):
      		"""基本随机数生成"""
      		print("=== 基本随机数 ===")
      		print(f"随机浮点数 [0,1): {random.random()}")
      		print(f"随机浮点数 [1,10): {random.uniform(1, 10)}")
      		print(f"随机整数 [1,100]: {random.randint(1, 100)}")
      		print(f"随机范围整数: {random.randrange(0, 100, 5)}")  # 0-100之间5的倍数
      
      	def sequence_operations(self):
      	    """序列操作"""
      	    items = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']
      	    
      	    print("\n=== 序列操作 ===")
      	    print(f"随机选择: {random.choice(items)}")
      	    print(f"随机选择多个: {random.choices(items, k=3)}")
      	    print(f"随机抽样(不重复): {random.sample(items, 3)}")
      	    
      	    # 打乱顺序
      	    shuffled = items.copy()
      	    random.shuffle(shuffled)
      	    print(f"打乱后: {shuffled}")
      	
      	def advanced_examples(self):
      	    """高级示例"""
      	    print("\n=== 高级示例 ===")
      	    
      	    # 加权随机选择
      	    choices = ['A', 'B', 'C']
      	    weights = [0.6, 0.3, 0.1]  # 概率权重
      	    weighted_choice = random.choices(choices, weights=weights, k=10)
      	    print(f"加权随机选择: {weighted_choice}")
      	    
      	    # 生成随机字符串
      	    random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
      	    print(f"随机字符串: {random_string}")
      	    
      	    # 生成随机颜色
      	    def random_color():
      	        return f"#{random.randint(0, 255):02x}{random.randint(0, 255):02x}{random.randint(0, 255):02x}"
      	    
      	    print(f"随机颜色: {random_color()}")
      	
      	def practical_applications(self):
      	    """实际应用"""
      	    print("\n=== 实际应用 ===")
      	    
      	    # 抽奖程序
      	    participants = ['张三', '李四', '王五', '赵六', '钱七']
      	    winner = random.choice(participants)
      	    print(f"中奖者: {winner}")
      	    
      	    # 验证码生成
      	    def generate_code(length=6):
      	        chars = string.digits  # 仅数字
      	        return ''.join(random.choices(chars, k=length))
      	    
      	    print(f"验证码: {generate_code()}")
      	    
      	    # 随机测试数据
      	    def generate_test_data(num_records=5):
      	        first_names = ['张', '李', '王', '赵', '刘']
      	        last_names = ['三', '四', '五', '六', '七']
      	        domains = ['example.com', 'test.com', 'sample.org']
      	        
      	        data = []
      	        for _ in range(num_records):
      	            name = random.choice(first_names) + random.choice(last_names)
      	            email = f"{name}@{random.choice(domains)}"
      	            age = random.randint(18, 60)
      	            data.append({'name': name, 'email': email, 'age': age})
      	        
      	        return data
      	    
      	    test_data = generate_test_data(3)
      	    print("随机测试数据:")
      	    for record in test_data:
      	        print(f"  姓名: {record['name']}, 邮箱: {record['email']}, 年龄: {record['age']}")
      
      # 使用示例
      random_example = RandomExamples()
      random_example.basic_random()
      random_example.sequence_operations()
      random_example.advanced_examples()
      random_example.practical_applications()
      
    1. Python3模块之PyQt5 (预计时间: 60min)
      PyQt5用于创建桌面应用程序的GUI框架。
      """
      安装: pip install PyQt5
      """
      # 简单的PyQt5应用示例
      try:
      	import sys
      	from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget,
      	QVBoxLayout, QHBoxLayout, QPushButton,
      	QLabel, QLineEdit, QTextEdit, QMessageBox,
      	QListWidget, QProgressBar)
      	from PyQt5.QtCore import QTimer, Qt
      	from PyQt5.QtGui import QFont, QIcon
      	
      	class SimpleApp(QMainWindow):
      	    def __init__(self):
      	        super().__init__()
      	        self.init_ui()
      	    
      	    def init_ui(self):
      	        """初始化用户界面"""
      	        self.setWindowTitle('PyQt5 示例应用')
      	        self.setGeometry(100, 100, 600, 400)
      	        
      	        # 中央部件
      	        central_widget = QWidget()
      	        self.setCentralWidget(central_widget)
      	        
      	        # 布局
      	        layout = QVBoxLayout()
      	        central_widget.setLayout(layout)
      	        
      	        # 标题
      	        title = QLabel('PyQt5 示例应用程序')
      	        title.setFont(QFont('Arial', 16, QFont.Bold))
      	        title.setAlignment(Qt.AlignCenter)
      	        layout.addWidget(title)
      	        
      	        # 输入区域
      	        input_layout = QHBoxLayout()
      	        self.name_input = QLineEdit()
      	        self.name_input.setPlaceholderText('请输入姓名...')
      	        input_layout.addWidget(QLabel('姓名:'))
      	        input_layout.addWidget(self.name_input)
      	        layout.addLayout(input_layout)
      	        
      	        # 按钮区域
      	        button_layout = QHBoxLayout()
      	        greet_btn = QPushButton('打招呼')
      	        clear_btn = QPushButton('清空')
      	        exit_btn = QPushButton('退出')
      	        
      	        greet_btn.clicked.connect(self.greet)
      	        clear_btn.clicked.connect(self.clear)
      	        exit_btn.clicked.connect(self.close)
      	        
      	        button_layout.addWidget(greet_btn)
      	        button_layout.addWidget(clear_btn)
      	        button_layout.addWidget(exit_btn)
      	        layout.addLayout(button_layout)
      	        
      	        # 显示区域
      	        self.output_text = QTextEdit()
      	        self.output_text.setReadOnly(True)
      	        layout.addWidget(self.output_text)
      	        
      	        # 进度条
      	        self.progress_bar = QProgressBar()
      	        self.progress_bar.setVisible(False)
      	        layout.addWidget(self.progress_bar)
      	        
      	        # 定时器用于进度条动画
      	        self.timer = QTimer()
      	        self.timer.timeout.connect(self.update_progress)
      	        self.progress_value = 0
      	    
      	    def greet(self):
      	        """打招呼按钮点击事件"""
      	        name = self.name_input.text().strip()
      	        if not name:
      	            QMessageBox.warning(self, '警告', '请输入姓名!')
      	            return
      	        
      	        self.output_text.append(f'你好, {name}! 欢迎使用PyQt5!')
      	        
      	        # 显示进度条
      	        self.progress_bar.setVisible(True)
      	        self.progress_value = 0
      	        self.progress_bar.setValue(0)
      	        self.timer.start(50)  # 每50毫秒更新一次
      	    
      	    def update_progress(self):
      	        """更新进度条"""
      	        self.progress_value += 2
      	        self.progress_bar.setValue(self.progress_value)
      	        
      	        if self.progress_value >= 100:
      	            self.timer.stop()
      	            QMessageBox.information(self, '完成', '操作完成!')
      	            self.progress_bar.setVisible(False)
      	    
      	    def clear(self):
      	        """清空按钮点击事件"""
      	        self.output_text.clear()
      	        self.name_input.clear()
      	        self.progress_bar.setVisible(False)
      	        self.timer.stop()
      
      	def run_qt_app():
      	    """运行Qt应用程序"""
      	    app = QApplication(sys.argv)
      	    window = SimpleApp()
      	    window.show()
      	    sys.exit(app.exec_())
      	
      	# 注释掉自动运行,让用户决定何时运行
      	# run_qt_app()
      except ImportError:
      	print("请安装PyQt5: pip install PyQt5")
      	# 控制台提示
      	print("PyQt5示例代码已准备就绪。要运行GUI应用,请取消注释 run_qt_app() 调用。")
      
    1. Python3模块之pymysql/pymssql (预计时间: 30min)
      数据库操作的高级应用。
      import pymysql
      from contextlib import contextmanager
      
      class AdvancedDBManager:
      	def init(self, db_type='mysql', **config):
      		self.db_type = db_type
      		self.config = config
      
      	@contextmanager
      	def get_connection(self):
      	    """上下文管理器,自动处理连接"""
      	    if self.db_type == 'mysql':
      	        conn = pymysql.connect(**self.config)
      	    else:
      	        # 对于SQL Server,使用pymssql
      	        import pymssql
      	        conn = pymssql.connect(**self.config)
      	    
      	    try:
      	        yield conn
      	    except Exception as e:
      	        conn.rollback()
      	        raise e
      	    finally:
      	        conn.close()
      	
      	def execute_query(self, query, params=None, fetch=True):
      	    """执行查询"""
      	    with self.get_connection() as conn:
      	        with conn.cursor() as cursor:
      	            cursor.execute(query, params)
      	            if fetch:
      	                if query.strip().upper().startswith('SELECT'):
      	                    return cursor.fetchall()
      	            conn.commit()
      	            return cursor.rowcount
      	
      	def batch_insert(self, table, data):
      	    """批量插入数据"""
      	    if not data:
      	        return 0
      	    
      	    # 生成插入语句
      	    columns = ', '.join(data[0].keys())
      	    placeholders = ', '.join(['%s'] * len(data[0]))
      	    query = f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"
      	    
      	    with self.get_connection() as conn:
      	        with conn.cursor() as cursor:
      	            # 准备数据
      	            values = [tuple(item.values()) for item in data]
      	            cursor.executemany(query, values)
      	            conn.commit()
      	            return cursor.rowcount
      	
      	def transaction_example(self):
      	    """事务处理示例"""
      	    with self.get_connection() as conn:
      	        try:
      	            with conn.cursor() as cursor:
      	                # 执行多个操作
      	                cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
      	                cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
      	                conn.commit()
      	                print("事务执行成功")
      	        except Exception as e:
      	            conn.rollback()
      	            print(f"事务执行失败: {e}")
      	
      	def create_user_table(self):
      	    """创建用户表"""
      	    query = """
      	    CREATE TABLE IF NOT EXISTS users (
      	        id INT AUTO_INCREMENT PRIMARY KEY,
      	        username VARCHAR(50) UNIQUE NOT NULL,
      	        email VARCHAR(100) UNIQUE NOT NULL,
      	        password_hash VARCHAR(255) NOT NULL,
      	        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      	        last_login TIMESTAMP NULL,
      	        is_active BOOLEAN DEFAULT TRUE
      	    )
      	    """
      	    self.execute_query(query, fetch=False)
      	    print("用户表创建成功")
      	    
      # 使用示例
      def demonstrate_db_operations():
      	# MySQL配置
      	mysql_config = {
      					'host': 'localhost',
      					'user': 'root',
      					'password': 'password',
      					'database': 'test_db',
      					'charset': 'utf8mb4'
      					}
      	db = AdvancedDBManager('mysql', **mysql_config)
      	
      	# 创建表
      	db.create_user_table()
      	
      	# 批量插入示例数据
      	users = [
      	    {'username': 'user1', 'email': 'user1@example.com', 'password_hash': 'hash1'},
      	    {'username': 'user2', 'email': 'user2@example.com', 'password_hash': 'hash2'},
      	    {'username': 'user3', 'email': 'user3@example.com', 'password_hash': 'hash3'}
      	]
      	affected = db.batch_insert('users', users)
      	print(f"插入了 {affected} 条记录")
      	
      	# 查询数据
      	users = db.execute_query("SELECT * FROM users WHERE is_active = TRUE")
      	print("活跃用户:")
      	for user in users:
      	    print(f"  ID: {user[0]}, 用户名: {user[1]}, 邮箱: {user[2]}")
      	
      	# 事务示例
      	db.transaction_example()
      	
      # 运行示例
      if name== "main":
      	demonstrate_db_operations()
      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值