【建议收藏】30个较难Python脚本,纯干货分享
本篇较难,建议优先学习上篇 ;20个硬核Python脚本-CSDN博客
接上篇文章,对于Pyhon的学习,上篇学习的结束相信大家对于Pyhon有了一定的理解和经验,学习完上篇文章之后再研究研究剩下的30个脚本你将会有所成就!加油!
目录
21、数据库连接 - SQLite
22、图像处理 - Pillow
23、图形界面 - Tkinter
24、文本生成 - Faker
25、加密和解密 - cryptography
26、Socket编程
27、并发编程 - threading
28、正则表达式 - re
29、REST API - FastAPI
30、数据库连接 - SQLAlchemy
31、文本处理 - NLTK
32、命令行应用 - argparse
33、微服务 - Flask-RESTful
34、数据处理 - BeautifulSoup
35、加密 - hashlib
36、数据序列化 - Pickle
37、并行处理 - concurrent.futures
38、网络爬虫 - Scrapy
39、异步编程 - asyncio
40、数据分析 - Numpy
41、数据处理 - Pandas
42、数据可视化 - Matplotlib
43、机器学习 - Scikit-Learn
44、机器学习 - Keras
45、图像处理 - OpenCV
46、数据爬取 - Scrapy
47、数据分析 - Seaborn
48、数据可视化 - Plotly
49、自然语言处理 - spaCy
50、机器学习 - XGBoost
21、数据库连接 - SQLite
import sqlite3conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
conn.commit()
conn.close()
官方文档: https://www.sqlite.org/docs.html
22、图像处理 - Pillow
from PIL import Imageimg = Image.open('example.jpg')
img.show()
官方文档: https://pillow.readthedocs.io/en/stable/index.html
23、图形界面 - Tkinter
import tkinter as tkroot = tk.Tk()
label = tk.Label(root, text="Hello, GUI!")
label.pack()
root.mainloop()
官方文档: https://docs.python.org/3/library/tkinter.html
24、文本生成 - Faker
from faker import Fakerfake = Faker()
print(fake.name())
官方文档: https://faker.readthedocs.io/en/master/
25、加密和解密 - cryptography
from cryptography.fernet import Fernetkey = Fernet.generate_key()
cipher_suite = Fernet(key)
text = "Secret message".encode()
cipher_text = cipher_suite.encrypt(text)
print(cipher_text)
官方文档: https://cryptography.io/en/latest/
26、Socket编程
import socketserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1', 12345))
server_socket.listen(5)
print("Server is listening...")while True:client_socket, addr = server_socket.accept()print(f"Connection from {addr}")client_socket.send(b"Hello, client!")client_socket.close()
官方文档: https://docs.python.org/3/library/socket.html
27、并发编程 - threading
import threadingdef print_numbers():for i in range(1, 6):print(f"Number: {i}")def print_letters():for letter in "abcde":print(f"Letter: {letter}")thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)thread1.start()
thread2.start()
官方文档: https://docs.python.org/3/library/threading.html
28、正则表达式 - re
import retext = "My phone number is 123-456-7890."
pattern = r'\d{3}-\d{3}-\d{4}'
match = re.search(pattern, text)
if match:print(f"Phone number found: {match.group()}")
官方文档: https://docs.python.org/3/howto/regex.html
29、REST API - FastAPI
from fastapi import FastAPIapp = FastAPI()@app.get("/items/{item_id}")
def read_item(item_id: int, query_param: str = None):return {"item_id": item_id, "query_param": query_param}
官方文档: https://fastapi.tiangolo.com/
30、数据库连接 - SQLAlchemy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_baseengine = create_engine('sqlite:///mydatabase.db')
Base = declarative_base()class User(Base):__tablename__ = 'users'id = Column(Integer, primary_key=True)name = Column(String)Session = sessionmaker(bind=engine)
session = Session()
官方文档: https://docs.sqlalchemy.org/en/20/
31、文本处理 - NLTK
import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenizetext = "This is a sample sentence."
tokens = word_tokenize(text)
print(tokens)
官方文档: https://www.nltk.org/
32、命令行应用 - argparse
import argparseparser = argparse.ArgumentParser(description='A simple command-line app')
parser.add_argument('--name', type=str, help='Your name')
args = parser.parse_args()
print(f'Hello, {args.name}!')
官方文档: https://docs.python.org/3/library/argparse.html
33、微服务 - Flask-RESTful
from flask import Flask
from flask_restful import Resource, Apiapp = Flask(__name)
api = Api(app)class HelloWorld(Resource):def get(self):return {'message': 'Hello, World!'}api.add_resource(HelloWorld, '/')
官方文档: https://flask-restful.readthedocs.io/en/latest/
34、数据处理 - BeautifulSoup
from bs4 import BeautifulSoup
import requestsurl = "https://www.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print(soup.title.text)
官方文档: https://www.crummy.com/software/BeautifulSoup/bs4/doc/
35、加密 - hashlib
import hashlibtext = "Secret Password"
hash_object = hashlib.sha256(text.encode())
hash_hex = hash_object.hexdigest()
print(hash_hex)
官方文档: https://docs.python.org/3/library/hashlib.html
36、数据序列化 - Pickle
import pickledata = {'name': 'Alice', 'age': 30}
with open('data.pkl', 'wb') as file:pickle.dump(data, file)with open('data.pkl', 'rb') as file:loaded_data = pickle.load(file)print(loaded_data)
官方文档: https://docs.python.org/3/library/pickle.html
37、并行处理 - concurrent.futures
import concurrent.futuresdef square(x):return x * xwith concurrent.futures.ThreadPoolExecutor() as executor:results = executor.map(square, [1, 2, 3, 4, 5])for result in results:print(result)
官方文档: https://docs.python.org/3/library/concurrent.futures.html
38、网络爬虫 - Scrapy
import scrapyclass MySpider(scrapy.Spider):name = 'example.com'start_urls = ['https://www.example.com']def parse(self, response):# 爬取和处理数据pass
官方文档: https://docs.scrapy.org/en/latest/
39、异步编程 - asyncio
import asyncioasync def hello():await asyncio.sleep(1)print("Hello, Async!")loop = asyncio.get_event_loop()
loop.run_until_complete(hello())
官方文档: https://docs.python.org/3/library/asyncio.html
40、数据分析 - Numpy
import numpy as nparr = np.array([1, 2, 3, 4, 5])
print(arr.mean())
官方文档: https://numpy.org/doc/stable/
41、数据处理 - Pandas
import pandas as pddata = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
print(df)
官方文档: https://pandas.pydata.org/docs/
42、数据可视化 - Matplotlib
import matplotlib.pyplot as pltx = [1, 2, 3, 4, 5]
y = [10, 15, 13, 18, 20]
plt.plot(x, y)
plt.show()
官方文档: https://matplotlib.org/stable/contents.html
43、机器学习 - Scikit-Learn
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifieriris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2)
clf = RandomForestClassifier(n_estimators=100)
clf.fit(X_train, y_train)
官方文档: https://scikit-learn.org/stable/documentation.html
44、机器学习 - Keras
from keras.models import Sequential
from keras.layers import Densemodel = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))
官方文档: https://keras.io/guides/
45、图像处理 - OpenCV
import cv2image = cv2.imread('image.jpg')
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
官方文档: https://docs.opencv.org/master/index.html
46、数据爬取 - Scrapy
import scrapyclass MySpider(scrapy.Spider):name = 'example.com'start_urls = ['https://www.example.com']def parse(self, response):# 爬取和处理数据pass
47、数据分析 - Seaborn
import seaborn as sns
import matplotlib.pyplot as pltdata = sns.load_dataset("iris")
sns.pairplot(data, hue="species")
plt.show()
官方文档: https://seaborn.pydata.org/introduction.html
48、数据可视化 - Plotly
import plotly.express as pxfig = px.scatter(x=[1, 2, 3, 4], y=[10, 11, 12, 13])
fig.show()
官方文档: https://plotly.com/python/
49、自然语言处理 - spaCy
import spacynlp = spacy.load('en_core_web_sm')
doc = nlp("This is a sample sentence.")
for token in doc:print(token.text, token.pos_)
官方文档: https://spacy.io/usage/spacy-101
50、机器学习 - XGBoost
import xgboost as xgbdata = xgb.DMatrix('train.csv')
param = {'max_depth': 3, 'eta': 0.1, 'objective': 'reg:squarederror'}
model = xgb.train(param, data, 10)
官方文档: https://xgboost.readthedocs.io/en/latest/
结束 over
相关文章:
【建议收藏】30个较难Python脚本,纯干货分享
本篇较难,建议优先学习上篇 ;20个硬核Python脚本-CSDN博客 接上篇文章,对于Pyhon的学习,上篇学习的结束相信大家对于Pyhon有了一定的理解和经验,学习完上篇文章之后再研究研究剩下的30个脚本你将会有所成就&…...
01-05.Vue自定义过滤器
目录 前言过滤器的概念过滤器的基本使用给过滤器添加多个参数 前言 我们接着上一篇文章01-04.Vue的使用示例:列表功能 来讲。 下一篇文章 02-Vue实例的生命周期函数 过滤器的概念 概念:Vue.js 允许我们自定义过滤器,可被用作一些常见的文本…...
C++系列-static成员
🌈个人主页:羽晨同学 💫个人格言:“成为自己未来的主人~” 概念 声明为static的类成员称为类的静态成员,用static修饰的成员变量,称之为静态成员变量,用static修饰的成员函数,称之为静态成…...
Git | 创建和管理Pull Request总结
如是我闻: 在使用 GitHub 进行项目协作时,掌握如何创建、更新和合并(squash)pull request 是非常有帮助的。本文将详细介绍这些操作,帮助我们更好地管理项目代码,并解释每个操作的原因和解决的问题。 1. 什…...
电机控制系列模块解析(23)—— 同步机初始位置辨识
一、两个常见问题 为什么感应电机(异步机)不需要初始位置辨识?(因此感应电机转子磁场在定子侧进行励磁,其初始位置可以始终人为定义为0) 为什么同步磁阻电机需要初始位置辨识?(因为…...
【数据库基础-mysql详解之索引的魅力(N叉树)】
索引的魅力目录 🌈索引的概念🌈使用场景🌈索引的使用🌞🌞🌞查看MySQL中的默认索引🌞🌞🌞创建索引🌞🌞🌞删除索引 站在索引背后的那个男…...
力扣739. 每日温度
Problem: 739. 每日温度 文章目录 题目描述思路复杂度Code 题目描述 思路 若本题目使用暴力法则会超时,故而使用单调栈解决: 1.创建结果数组res,和单调栈stack; 2.循环遍历数组temperatures: 2.1.若当stack不为空同时…...
KDE6桌面于2024年2月发布
原文:KDE MegaRelease 6 - KDE 社区 1. **Plasma 6 桌面环境**:KDE Plasma 是一个现代化、功能丰富的 Linux 操作系统桌面环境,以其时尚设计、可定制界面和广泛的应用程序而闻名。Plasma 6 带来了两项重大技术升级:过渡到最新的应…...
「TypeScript系列」TypeScript 对象及对象的使用场景
文章目录 一、TypeScript 对象1. 对象字面量2. 类实例化3. 使用接口定义对象形状4. 使用类型别名定义对象类型5. 使用工厂函数创建对象 二、TypeScript 对象属性及方法1. 对象属性2. 对象方法3. 访问器和修改器(Getters 和 Setters) 三、TypeScript 对象…...
shell从入门到精通(22)shell正则匹配~=
文章目录 1. 基本用法2. 正则表达式捕获组(catch group)3. 匹配结果提取1. 基本用法 在 Shell 脚本中,可以使用正则表达式进行文本匹配和提取。Bash shell 支持使用 [[ … =~ … ]] 结构进行正则表达式匹配,同时还能提取匹配结果。 以下是一个简单的例子,展示了如何在 Bas…...
【Spring】使用Spring常用导入依赖介绍
当使用Spring框架时,以下是常用导入的依赖的详细介绍,按照不同的功能和类别进行分点表示和归纳: 1、核心依赖 Spring Core (spring-core) 功能:提供了Spring框架的基础功能,包括IoC(控制反转)…...
PC端应用订阅SDK接入攻略
本文档介绍了联想应用联运sdk接入操作指南,您可在了解文档内容后,自行接入应用联运sdk。 1. 接入前准备 1. 请先与联想商务达成合作意向。 2. 联系联想运营,提供应用和公司信息,并获取商户id、app id、key(公私钥、…...
WebService的wsdl详解
webservice服务的wsdl内容详解,以及如何根据其内容编写调用代码 wsdl示例 展示一个webservice的wsdl,及调用这个接口的Axis客户端 wsdl This XML file does not appear to have any style information associated with it. The document tree is shown…...
数据分析实战:从0到1完成数据获取分析到可视化
文章目录 1.数据分析基本流程1.1 数据采集1.2 数据提炼1.3 数据探索分析 2.数据获取的方法和工具2.1 数据解锁器2.2 爬虫浏览器2.3 数据洞察市场 3.完整案例分析:从数据采集到数据可视化3.1 直接按需定制数据集获取数据3.2 获取IP代理,利用python爬取数据…...
【Spring】深入理解 Spring 中的 ImportSelector、Aware 和 Processor 接口
前言 Spring 框架提供了一系列接口和机制,为开发者提供了灵活、可扩展的编程模型。其中,ImportSelector、Aware 接口以及 Processor 系列接口是非常重要的扩展点,本文将深入探讨它们的设计目的、使用方法以及示例应用。 一、ImportSelector…...
【C语言】strstr函数的使用和模拟
前言 今天给大家带来一个字符串函数,strstr()的使用介绍和模拟实现。 模拟实现这个函数,可以帮助我们更深刻地理解这个函数的功能和提高解决字符串相关问题的能力,有兴趣的话就请往下看吧。 strstr函数介绍 函数功能: strstr函…...
五分钟”手撕“异常
目录 一、什么是异常 二、异常的体系和分类 三、异常的处理 1.抛出异常 2.异常的捕获 异常声明throws: try-catch处理 四、finally finally一定会被执行吗? 五、throw和throws区别 六、异常处理的流程 七、自定义异常 一、什么是异常 顾名…...
【vue3+elementuiplus】el-select下拉框会自动触发校验规则
场景:编辑弹框省份字段下拉框必填,触发方式change,有值第一次打开不会触发校验提示,关闭弹框再次打开触发必填校验提示,但是该字段有值 问题的原因是:在关闭弹层事件中,我做了resetfileds&…...
【论文复现】LSTM长短记忆网络
LSTM 前言网络架构总线遗忘门记忆门记忆细胞输出门 模型定义单个LSTM神经元的定义LSTM层内结构的定义 模型训练模型评估代码细节LSTM层单元的首尾的处理配置Tensorflow的GPU版本 前言 LSTM作为经典模型,可以用来做语言模型,实现类似于语言模型的功能&am…...
目标检测YOLO实战应用案例100讲-【自动驾驶】激光雷达
目录 前言 算法原理 测距方法 发射单元 接收单元 扫描单元...
遍历 Map 类型集合的方法汇总
1 方法一 先用方法 keySet() 获取集合中的所有键。再通过 gey(key) 方法用对应键获取值 import java.util.HashMap; import java.util.Set;public class Test {public static void main(String[] args) {HashMap hashMap new HashMap();hashMap.put("语文",99);has…...
java调用dll出现unsatisfiedLinkError以及JNA和JNI的区别
UnsatisfiedLinkError 在对接硬件设备中,我们会遇到使用 java 调用 dll文件 的情况,此时大概率出现UnsatisfiedLinkError链接错误,原因可能有如下几种 类名错误包名错误方法名参数错误使用 JNI 协议调用,结果 dll 未实现 JNI 协…...
pam_env.so模块配置解析
在PAM(Pluggable Authentication Modules)配置中, /etc/pam.d/su 文件相关配置含义如下: 配置解析 auth required pam_env.so1. 字段分解 字段值说明模块类型auth认证类模块,负责验证用户身份&am…...
分布式增量爬虫实现方案
之前我们在讨论的是分布式爬虫如何实现增量爬取。增量爬虫的目标是只爬取新产生或发生变化的页面,避免重复抓取,以节省资源和时间。 在分布式环境下,增量爬虫的实现需要考虑多个爬虫节点之间的协调和去重。 另一种思路:将增量判…...
力扣-35.搜索插入位置
题目描述 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 请必须使用时间复杂度为 O(log n) 的算法。 class Solution {public int searchInsert(int[] nums, …...
HashMap中的put方法执行流程(流程图)
1 put操作整体流程 HashMap 的 put 操作是其最核心的功能之一。在 JDK 1.8 及以后版本中,其主要逻辑封装在 putVal 这个内部方法中。整个过程大致如下: 初始判断与哈希计算: 首先,putVal 方法会检查当前的 table(也就…...
【JVM】Java虚拟机(二)——垃圾回收
目录 一、如何判断对象可以回收 (一)引用计数法 (二)可达性分析算法 二、垃圾回收算法 (一)标记清除 (二)标记整理 (三)复制 (四ÿ…...
Golang——6、指针和结构体
指针和结构体 1、指针1.1、指针地址和指针类型1.2、指针取值1.3、new和make 2、结构体2.1、type关键字的使用2.2、结构体的定义和初始化2.3、结构体方法和接收者2.4、给任意类型添加方法2.5、结构体的匿名字段2.6、嵌套结构体2.7、嵌套匿名结构体2.8、结构体的继承 3、结构体与…...
Java 与 MySQL 性能优化:MySQL 慢 SQL 诊断与分析方法详解
文章目录 一、开启慢查询日志,定位耗时SQL1.1 查看慢查询日志是否开启1.2 临时开启慢查询日志1.3 永久开启慢查询日志1.4 分析慢查询日志 二、使用EXPLAIN分析SQL执行计划2.1 EXPLAIN的基本使用2.2 EXPLAIN分析案例2.3 根据EXPLAIN结果优化SQL 三、使用SHOW PROFILE…...
边缘计算网关提升水产养殖尾水处理的远程运维效率
一、项目背景 随着水产养殖行业的快速发展,养殖尾水的处理成为了一个亟待解决的环保问题。传统的尾水处理方式不仅效率低下,而且难以实现精准监控和管理。为了提升尾水处理的效果和效率,同时降低人力成本,某大型水产养殖企业决定…...
