以下是九个常见的实用Python实例,涵盖了不同领域和应用
文本处理:统计文本中单词出现的频率
text = "This is a sample text for word frequency analysis."
words = text.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count)
文件操作:复制文件
import shutil
src_file = 'source.txt'
dest_file = 'destination.txt'
shutil.copyfile(src_file, dest_file)
网络请求:发送GET请求并获取响应内容
import requests
url = 'https://api.example.com/data'
response = requests.get(url)
print(response.text)
数据解析:解析JSON数据
import json
json_data = '{"name": "John", "age": 25}'
data = json.loads(json_data)
print(data['name'])
数据库操作:连接SQLite数据库并执行查询
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
图像处理:调整图像大小
from PIL import Image
image = Image.open('image.jpg')
resized_image = image.resize((800, 600))
resized_image.save('resized_image.jpg')
数据科学:使用NumPy进行矩阵操作
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
result = np.dot(matrix1, matrix2)
print(result)
Web自动化:使用Selenium模拟浏览器行为
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.example.com')
element = driver.find_element_by_id('element_id')
print(element.text)
driver.close()
数据可视化:绘制折线图
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 8, 6, 4, 2]
plt.plot(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Line Graph')
plt.show()
这些实例覆盖了Python编程中各个领域的常见应用。您可以根据自己的兴趣和需求进一步探索和扩展这些实例,以及研究其他有用的Python库和功能。