27个实用Python实例

1. 文件操作:

# 创建文件并写入内容``with open('example.txt', 'w') as file:`    `file.write('Hello, world!')`    `# 读取文件内容``with open('example.txt', 'r') as file:`    `content = file.read()`    `print(content)

2. 网络请求:

import requests``# 发送GET请求并获取响应内容``response = requests.get('https://api.github.com')``print(response.text)

3. 数据库连接:

import sqlite3``# 连接数据库并执行查询``conn = sqlite3.connect('example.db')``cursor = conn.cursor()``cursor.execute('SELECT * FROM users')``results = cursor.fetchall()``# 打印查询结果``for row in results:`    `print(row)``# 关闭连接``conn.close()

4. 数据分析

import pandas as pd``# 读取CSV文件``data = pd.read_csv('data.csv')``# 统计数据``mean = data.mean()``max_value = data.max()``# 打印统计结果``print(mean)``print(max_value)

5. 图像处理

from PIL import Image``# 打开图像文件``image = Image.open('image.jpg')``# 调整尺寸``resized_image = image.resize((500, 500))``# 保存处理后的图像``resized_image.save('resized_image.jpg')

6. 文本处理:

# 拆分句子``sentence = 'Hello, how are you?'``words = sentence.split(' ')``print(words)``   ``   ``# 替换字符串``text = 'Hello, world!'``new_text = text.replace('world', 'Python')``print(new_text)

7. 时间处理

from datetime import datetime``# 获取当前时间``now = datetime.now()``print(now)``# 格式化时间``formatted_time = now.strftime('%Y-%m-%d %H:%M:%S')``print(formatted_time)

8. 正则表达式

import re``# 匹配邮箱地址``email = 'example@example.com'``pattern = r'^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$'``match = re.match(pattern, email)``if match:`    `print('Valid email')``else:`    `print('Invalid email')

9. GUI应用</

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值