在这个列表中,我们收集了 20 个有趣的东西,它们不仅有趣而且实用。无论您是编码爱好者还是只是在寻找有用的工具,这些脚本都能满足您的需求。
1.带有BeautifulSoup和请求的Web Scraper:
目标:创建一个简单的网络抓取工具,使用 Python 从网站中提取数据。
import requests from bs4 import BeautifulSoup url = 'https://example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # Extracting data, e.g., all the links on the page links = soup.find_all('a') for link in links: print(link.get('href'))
|
解释:
- requests.get(url):获取指定URL的HTML内容。
- BeautifulSoup(response.text, 'html.parser'):解析HTML内容。
- soup.find_all('a'):查找所有锚标记。
- link.get('href'):检索每个锚标记的 href 属性。
2. 使用 Flask 部署机器学习模型:
目标:构建Flask Web 应用程序来部署机器学习模型并进行预测。
from flask import Flask, request, jsonify import pickle app = Flask(__name__) # Load the trained machine learning model with open('model.pkl', 'rb') as model_file: model = pickle.load(model_file) @app.route('/predict', methods=['POST']) def predict(): data = request.get_json(force=True) prediction = model.predict([data['input']]) output = {'prediction': prediction[0]} return jsonify(output) if __name__ == '__main__': app.run(port=5000)
|
解释:
- Flask:Python 的 Web 框架。
- pickle:用于序列化和反序列化机器学习模型。
- @app.route('/predict', methods=['POST']):定义进行预测的端点。
- request.get_json(force=True):检索 JSON 格式的输入数据。
- model.predict([data['input']]):使用经过训练的模型进行预测。
该脚本设置一个 Flask Web 服务器,加载预先训练的机器学习模型并公开用于进行预测的端点。3. Python 中的区块链实现:
目标:创建一个基本的区块链系统,了解区块链技术的基本概念。
import hashlib import time class Block: def __init__(self, previous_hash, data): self.timestamp = time.time() self.previous_hash = previous_hash self.data = data self.hash = self.calculate_hash() def calculate_hash(self): return hashlib.sha256( (str(self.timestamp) + str(self.previous_hash) + str(self.data)).encode('utf-8') ).hexdigest() # Create a blockchain blockchain = [Block("0", "Genesis Block")] # Add a new block new_data = "Some transaction data" previous_block = blockchain[-1] new_block = Block(previous_block.hash, new_data) blockchain.append(new_block)
|
解释:
- hashlib.sha256():生成 SHA-256 哈希值。
- Block:表示区块链中的一个块,包含时间戳、数据、先前哈希值和当前哈希值。
- calculate_hash():使用块的属性计算块的哈希值。
该脚本使用创世块初始化区块链,并添加带有一些交易数据的新块。4. 使用 Selenium 进行自动化测试:
目标:使用 Selenium 编写 Python 脚本来自动执行 Web 应用程序的浏览器测试。
from selenium import webdriver # Initialize a Chrome browser driver = webdriver.Chrome() # Open a website driver.get('https://example.com') # Find an element by its ID and interact with it element = driver.find_element_by_id('some_element_id') element.click() # Perform assertions or other actions as needed # Close the browser driver.quit()
|
解释:
- webdriver.Chrome():初始化 Chrome 浏览器。
- driver.get('https://example.com'):打开一个网站。
- driver.find_element_by_id('some_element_id'):通过 ID 查找元素。
- element.click():与元素交互(例如,单击按钮)。
该脚本自动执行浏览器交互以测试 Web 应用程序。5. 使用 Scapy 进行网络扫描:
目标:使用 Scapy 库开发网络扫描仪来发现本地网络上的设备。
from scapy.all import ARP, Ether, srp def scan(ip): arp_request = ARP(pdst=ip) ether = Ether(dst="ff:ff:ff:ff:ff:ff") packet = ether/arp_request result = srp(packet, timeout=3, verbose=0)[0] devices = [] for sent, received in result: devices.append({'ip': received.psrc, 'mac': received.hwsrc}) return devices ip_range = "192.168.1.1/24" devices = scan(ip_range) for device in devices: print(f"IP: {device['ip']}, MAC: {device['mac']}")
|
解释:
- scapy.all:一个强大的数据包操作库。
- ARP:表示ARP请求报文。
- Ether:代表以太网帧。
- srp:在数据链路层发送和接收数据包。
该脚本对指定的 IP 范围执行 ARP 扫描以发现本地网络上的设备。6. 带 API 的加密货币价格跟踪器:
目标:构建一个使用加密货币 API 获取实时加密货币价格的脚本。
import requests def get_crypto_prices(): url = 'https://api.coingecko.com/api/v3/simple/price' params = {'ids': 'bitcoin,ethereum,litecoin', 'vs_currencies': 'usd'} response = requests.get(url, params=params) prices = response.json() return prices crypto_prices = get_crypto_prices() for coin, value in crypto_prices.items(): print(f"{coin.capitalize()}: ${value['usd']}")
|
解释:
- requests.get(url, params=params):使用指定参数向 CoinGecko API 发送 HTTP GET 请求。
- response.json():解析 JSON 响应。
- 以美元打印比特币、以太坊和莱特币的当前价格。
该脚本获取并显示实时加密货币价格。7. 使用 Pandas 和 Matplotlib 进行数据分析:
Objective:使用 Pandas 进行数据操作并使用 Matplotlib 进行绘图来分析和可视化数据集。
import pandas as pd import matplotlib.pyplot as plt # Assume 'data.csv' is your dataset df = pd.read_csv('data.csv') # Perform data analysis average_age = df['Age'].mean() total_records = len(df) # Create a bar chart plt.bar(['Average Age', 'Total Records'], [average_age, total_records]) plt.xlabel('Metrics') plt.ylabel('Values') plt.title('Basic Data Analysis') plt.show()
|
解释:
- pd.read_csv('data.csv'):将 CSV 文件读入 Pandas DataFrame。
- df['Age'].mean():从“年龄”列计算平均年龄。
- len(df):获取数据集中的记录总数。
- plt.bar(...):使用 Matplotlib 创建条形图。
该脚本执行基本数据分析并生成条形图。8. 自然语言处理 (NLP) 与 NLTK:
目标:使用自然语言工具包 (NLTK) 执行基本的 NLP 任务,例如标记化和情感分析。
import nltk from nltk.tokenize import word_tokenize, sent_tokenize from nltk.sentiment import SentimentIntensityAnalyzer nltk.download('punkt') nltk.download('vader_lexicon') text = "NLTK is a powerful library for natural language processing. I love using it!" # Tokenization words = word_tokenize(text) sentences = sent_tokenize(text) # Sentiment analysis sid = SentimentIntensityAnalyzer() sentiment_score = sid.polarity_scores(text) print("Tokenized Words:", words) print("Tokenized Sentences:", sentences) print("Sentiment Score:", sentiment_score)
|
解释:
- word_tokenize和sent_tokenize:将文本标记为单词和句子。
- SentimentIntensityAnalyzer:NLTK 的情感分析工具。
此脚本演示了使用 NLTK 的基本文本标记化和情感分析。9.数据加密/解密的Python脚本:
目标:实现使用加密算法加密和解密数据的脚本。
from cryptography.fernet import Fernet # Generate a key for encryption and decryption key = Fernet.generate_key() cipher_suite = Fernet(key) # Data to be encrypted data = b"Confidential information" # Encryption cipher_text = cipher_suite.encrypt(data) print("Encrypted:", cipher_text) # Decryption plain_text = cipher_suite.decrypt(cipher_text) print("Decrypted:", plain_text.decode('utf-8'))
|
解释:
- Fernet:一种对称密钥加密算法。
- Fernet.generate_key():生成用于加密和解密的密钥。
- cipher_suite.encrypt(data):对数据进行加密。
- cipher_suite.decrypt(cipher_text):解密数据。
该脚本演示了使用 Fernet 库进行基本数据加密和解密。10. 使用 Flask 创建 RESTful API:
目标:使用 Flask 构建 RESTful API 来提供和使用数据。
from flask import Flask, jsonify, request app = Flask(__name__) # Sample data books = [ {'id': 1, 'title': 'Python Crash Course', 'author': 'Eric Matthes'}, {'id': 2, 'title': 'Fluent Python', 'author': 'Luciano Ramalho'} ] # GET request to retrieve all books @app.route('/books', methods=['GET']) def get_books(): return jsonify({'books': books}) # POST request to add a new book @app.route('/books', methods=['POST']) def add_book(): new_book = request.get_json() books.append(new_book) return jsonify({'message': 'Book added successfully'}) if __name__ == '__main__': app.run(port=5000)
|
解释:
- @app.route('/books', methods=['GET']):定义检索所有书籍的端点。
- @app.route('/books', methods=['POST']):定义添加新书的端点。
- request.get_json():从请求中检索 JSON 数据。
该脚本设置了一个简单的 RESTful API 来管理图书列表。11. 使用 OpenCV 进行图像处理:
目标:使用 OpenCV 开发用于基本图像处理任务的脚本,例如边缘检测或颜色过滤。
import cv2 import numpy as np # Load an image image = cv2.imread('image.jpg') # Convert the image to grayscale gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Perform edge detection edges = cv2.Canny(gray_image, 50, 150) # Display the original and processed images cv2.imshow('Original Image', image) cv2.imshow('Edge Detection', edges) cv2.waitKey(0) cv2.destroyAllWindows()
|
解释:
- cv2.imread('image.jpg'):从文件中读取图像。
- cv2.cvtColor(image, cv2.COLOR_BGR2GRAY):将图像转换为灰度。
- cv2.Canny(gray_image, 50, 150):使用 Canny 算法应用边缘检测。
- cv2.imshow(...):显示图像。
该脚本演示了使用 OpenCV 进行基本图像处理。12.利用机器学习预测股价:
目标:训练机器学习模型以使用历史数据预测股票价格。
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt # Assume 'stock_data.csv' contains historical stock prices df = pd.read_csv('stock_data.csv') # Feature engineering df['Date'] = pd.to_datetime(df['Date']) df['Date'] = df['Date'].dt.strftime('%Y%m%d').astype(float) # Selecting features and target X = df[['Date']] y = df['Close'] # Split the data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Train a linear regression model model = LinearRegression() model.fit(X_train, y_train) # Make predictions predictions = model.predict(X_test) # Plot the predictions against actual values plt.scatter(X_test, y_test, color='black') plt.plot(X_test, predictions, color='blue', linewidth=3) plt.xlabel('Date') plt.ylabel('Stock Price (Close)') plt.title('Stock Price Prediction') plt.show()
|
解释:
- pd.read_csv('stock_data.csv'):从 CSV 文件中读取历史股价数据。
- train_test_split:将数据分为训练集和测试集。
- LinearRegression():初始化线性回归模型。
- model.fit(X_train, y_train):根据训练数据训练模型。
- model.predict(X_test):对测试数据进行预测。
该脚本说明了使用线性回归的基本股票价格预测。13. 自动电子邮件发送器:
目标:编写一个脚本以使用smtplib库发送自动电子邮件。
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # Sender and recipient email addresses sender_email = 'your_email@gmail.com' recipient_email = 'recipient_email@example.com' # Email server configuration smtp_server = 'smtp.gmail.com' smtp_port = 587 smtp_username = 'your_email@gmail.com' smtp_password = 'your_email_password' # Message content subject = 'Automated Email' body = 'This is an automated email sent using Python.' # Create the MIME object message = MIMEMultipart() message['From'] = sender_email message['To'] = recipient_email message['Subject'] = subject message.attach(MIMEText(body, 'plain')) # Connect to the SMTP server and send the email with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(smtp_username, smtp_password) server.sendmail(sender_email, recipient_email, message.as_string())
|
解释:
- smtplib.SMTP:建立与 SMTP 服务器的连接。
- MIMEText和MIMEMultipart:用于撰写电子邮件消息。
该脚本演示了如何使用 Python 发送自动电子邮件。14. 使用 ChatterBot 实现聊天机器人:
目标:使用 ChatterBot 库创建一个简单的聊天机器人以进行自然语言对话。
from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer # Create a chatbot instance chatbot = ChatBot('MyBot') # Create a new trainer for the chatbot trainer = ChatterBotCorpusTrainer(chatbot) # Train the chatbot on English language data trainer.train('chatterbot.corpus.english') # Get a response from the chatbot response = chatbot.get_response('Hello, how are you?') print(response)
|
解释:
- ChatterBot:代表聊天机器人。
- ChatterBotCorpusTrainer:使用语料库数据的聊天机器人训练器。
- trainer.train('chatterbot.corpus.english'):使用英语数据训练聊天机器人。
该脚本设置一个聊天机器人并演示与它的对话。15. 带 ReportLab 的自动 PDF 生成器:
目标:构建一个脚本以使用 ReportLab 库动态生成 PDF 报告。
from reportlab.pdfgen import canvas def generate_pdf(file_name, content): # Create a PDF document pdf = canvas.Canvas(file_name) # Add content to the PDF pdf.drawString(100, 750, "Generated PDF Report") pdf.drawString(100, 730, "----------------------") pdf.drawString(100, 700, content) # Save the PDF pdf.save() # Example usage report_content = "This is a sample PDF report." generate_pdf('sample_report.pdf', report_content)
|
解释:
- canvas.Canvas:创建用于绘图的 PDF 画布。
- pdf.drawString(x, y, text):将文本添加到 PDF 的指定坐标处。
该脚本使用 ReportLab 库生成一个简单的 PDF 报告。16. 使用 Scrapy 进行网页抓取:
目标:使用 Scrapy 框架开发一个网络爬虫,从网站中提取结构化数据。
import scrapy class QuotesSpider(scrapy.Spider): name = 'quotes' start_urls = ['http://quotes.toscrape.com/page/1/'] def parse(self, response): for quote in response.css('div.quote'): yield { 'text': quote.css('span.text::text').get(), 'author': quote.css('small::text').get(), 'tags': quote.css('div.tags a.tag::text').getall(), } next_page = response.css('li.next a::attr(href)').get() if next_page is not None: yield response.follow(next_page, self.parse)
|
解释:
- scrapy.Spider:定义用于网络抓取的蜘蛛。
- response.css(...):使用 CSS 选择器从 HTML 中提取数据。
- yield {...}:产生抓取的数据。
- response.follow(next_page, self.parse):跟随链接到后续页面。
该脚本代表一个基本的 Scrapy 蜘蛛,用于从网站中提取报价。17. Twitter 机器人与 Tweepy:
目标:使用 Tweepy 库创建一个简单的 Twitter 机器人来发布推文。
import tweepy import time # Twitter API credentials consumer_key = 'your_consumer_key' consumer_secret = 'your_consumer_secret' access_token = 'your_access_token' access_token_secret = 'your_access_token_secret' # Authenticate with Twitter auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) # Tweet content tweet_text = "Hello, Twitter! This is my first tweet using Tweepy." # Post the tweet api.update_status(tweet_text) # Wait for 5 seconds (optional) time.sleep(5)
|
解释:
- tweepy.OAuthHandler:使用 Twitter API 进行身份验证。
- api.update_status(tweet_text): 发了一条推文。
此脚本演示了如何使用 Tweepy 创建简单的 Twitter 机器人。18. 使用 Plotly 进行数据可视化:
目标:使用 Plotly 库创建交互式数据可视化。
import plotly.express as px import plotly.graph_objects as go # Sample data data = {'Category': ['A', 'B', 'C', 'D'], 'Values': [10, 25, 15, 30]} # Create a bar chart using Plotly Express fig1 = px.bar(data, x='Category', y='Values', title='Bar Chart') # Create a scatter plot using Plotly Graph Objects fig2 = go.Figure() fig2.add_trace(go.Scatter(x=data['Category'], y=data['Values'], mode='markers', name='Scatter Plot')) # Show the visualizations fig1.show() fig2.show()
|
解释:
- plotly.express:提供用于创建可视化的高级界面。
- plotly.graph_objects:允许更多的可视化定制。
该脚本展示了如何使用 Plotly Express 创建条形图以及使用 Plotly Graph 对象创建散点图。19. 使用 Tkinter 的 GUI 应用程序:
目标:使用 Tkinter 库开发一个简单的 GUI 应用程序。
import tkinter as tk def on_button_click(): label.config(text="Hello, " + entry.get()) # Create the main window window = tk.Tk() window.title("Simple Tkinter App") # Create a label label = tk.Label(window, text="Enter your name:") label.pack() # Create an entry widget entry = tk.Entry(window) entry.pack() # Create a button button = tk.Button(window, text="Click me", command=on_button_click) button.pack() # Run the application window.mainloop()
|
解释:
- tkinter:Python 的标准 GUI 工具包。
- tk.Label、tk.Entry、tk.Button:用于创建标签、输入字段和按钮的小部件。
- window.mainloop():启动 GUI 的事件循环。
该脚本演示了一个带有输入字段、按钮和标签的简单 Tkinter 应用程序。20. 具有数据库集成的 Flask Web 应用程序:
目标:使用 Flask 构建 Web 应用程序并集成 SQLite 数据库。
from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db' db = SQLAlchemy(app) # Define a data model class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) # Create the database db.create_all() @app.route('/') def index(): users = User.query.all() return render_template('index.html', users=users) @app.route('/add_user', methods=['POST']) def add_user(): username = request.form['username'] new_user = User(username=username) db.session.add(new_user) db.session.commit() return redirect(url_for('index')) if __name__ == '__main__': app.run(debug=True)
|
解释:
- Flask:Python 的 Web 框架。
- Flask_SQLAlchemy:用于将 SQLAlchemy 与 Flask 集成的扩展。
- User(db.Model):代表数据库中用户的数据模型。
- db.create_all():创建数据库表。
该脚本设置了一个带有 SQLite 数据库集成的简单 Flask Web 应用程序。总结
在本次 Python 之旅中,您探索了涵盖不同应用程序的各种脚本 - 从网络抓取到机器学习、数据分析、自动化和 Web 开发。无论您是制作聊天机器人、预测股票价格还是创建 Web 应用程序,这些脚本都展示了 Python 的多功能性和强大功能。