当前位置: 首页 > news >正文

【建议收藏】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讲-【自动驾驶】激光雷达

目录 前言 算法原理 测距方法 发射单元 接收单元 扫描单元...

93、【Agent】【OpenCode】edit 工具提示词(二)

【声明】本博客所有内容均为个人业余时间创作,所述技术案例均来自公开开源项目(如Github,Apache基金会),不涉及任何企业机密或未公开技术,如有侵权请联系删除 背景 上篇 blog 【Agent】【OpenCode】edit 工…...

2026照片去水印免费软件app详细教程:保姆级指南,一看就会

你是不是也遇到过这些尴尬时刻——辛辛苦苦刷到一张绝美壁纸,保存下来却发现右下角赫然挂着平台水印,当头像嫌脏、做素材嫌low;想从自己发的抖音视频里截一张封面图,结果水印刚好糊在脸上;又或者,老板甩过来…...

第41天:MySQL新特性

Python学习100天(从入门到精通系列文章) 文章目录 Python学习100天(从入门到精通系列文章) 前言 一、JSON类型 1.1 JSON类型的基本形式 1.2 JSON类型的实际应用场景 1.3 用户画像场景中的JSON应用 二、窗口函数 2.1 窗口函数的概念 2.2 窗口函数实战示例 总结 前言 在掌握…...

Arknights-Mower:解放双手的明日方舟智能基建管理工具

Arknights-Mower:解放双手的明日方舟智能基建管理工具 【免费下载链接】arknights-mower 《明日方舟》长草助手 项目地址: https://gitcode.com/gh_mirrors/ar/arknights-mower 在《明日方舟》的日常游戏过程中,基建管理、资源刷取和日常任务占据…...

为什么92%的DeepSeek生产环境存在越权风险?——企业级访问策略配置检查表,限免领取24小时

更多请点击: https://intelliparadigm.com 第一章:DeepSeek访问控制配置的现状与风险全景 当前,DeepSeek系列模型在企业私有化部署场景中广泛采用基于API密钥与角色权限分离的访问控制机制。然而,大量实际配置案例表明&#xff0…...

UnityExplorer自由视角相机完整指南:突破游戏视角限制的终极方案

UnityExplorer自由视角相机完整指南:突破游戏视角限制的终极方案 【免费下载链接】UnityExplorer An in-game UI for exploring, debugging and modifying IL2CPP and Mono Unity games. 项目地址: https://gitcode.com/gh_mirrors/un/UnityExplorer UnityEx…...

从注册到第一笔消费Taotoken新手指南与核心功能全景

🚀 告别海外账号与网络限制!稳定直连全球优质大模型,限时半价接入中。 👉 点击领取海量免费额度 从注册到第一笔消费:Taotoken 新手指南与核心功能全景 应用场景类,面向完全新接触 Taotoken 平台的用户&am…...

表面等离子体神经网络:微波感知技术的革命性突破

1. 表面等离子体神经网络:微波感知的技术革命在自动驾驶和智能物联网领域,微波感知技术正面临一个根本性挑战:传统毫米波雷达受限于数字信号处理的串行链路,系统刷新率被限制在几百赫兹量级。这种瓶颈直接影响了系统对动态场景的实…...

macOS上VirtualBox虚拟机卡顿?试试这个‘丝滑’增强包(含CentOS 7依赖安装避坑)

macOS上VirtualBox虚拟机卡顿终极优化指南:从依赖安装到性能调优刚在Mac上装好VirtualBox虚拟机,满心欢喜准备大展拳脚,却发现鼠标移动像在糖浆里游泳?窗口拖拽时仿佛在跟系统拔河?这种体验简直让人想摔键盘。别急着放…...

VisualGGPK2游戏资源编辑器:流放之路玩家的终极MOD制作指南

VisualGGPK2游戏资源编辑器:流放之路玩家的终极MOD制作指南 【免费下载链接】VisualGGPK2 Library for Content.ggpk of PathOfExile (Rewrite of libggpk) 项目地址: https://gitcode.com/gh_mirrors/vi/VisualGGPK2 你是否曾经想要修改《流放之路》的游戏界…...