【建议收藏】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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/840521.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Transformer详解(2)-位置编码

位置编码公式 偶数位置用sin,奇数位置用cos. d_model 表示token的维度;pos表示token在序列中的位置;i表示每个token编码的第i个位置,属于[0,d_model)。 torch实现 import math import torch from torch import nn from torch.autograd im…

pycharm配置python开发环境—miniconda+black+gitlab

下载miniconda管理python开发环境 miniconda下载地址:https://docs.anaconda.com/free/miniconda/ miniconda最新版本的python版本是python3.12.2,下载这个miniconda最新版本后,会导致执行conda create -n py31013 python3.10.13指令配置py…

如何设计电商 SaaS 系统中的免费服务和增值服务

随着电子商务的迅猛发展,越来越多的企业选择使用 SaaS(Software as a Service)平台来搭建自己的电商系统。为了吸引更多用户,电商 SaaS 系统通常会提供免费服务和增值服务。如何合理地设计这些服务,既能吸引新用户&…

使用HTTP长连接减少文件描述符和端口占用

在当今互联网技术飞速发展的背景下,高并发处理能力已经成为衡量服务器性能的一个重要标准。面对高并发场景,服务器需要同时应对大量的请求,这就带来了一个棘手的问题:资源有限。具体来说,文件描述符和端口号&#xff0…

ES实例演示一

温馨提示:本文所有API操作都是基于Elasticsearch 7.17 .8版本 1、文档的基本 CRUD 与批量操作 ############Create Document############ #create document. 自动生成 _id POST users/_doc {"user" : "Mike","post_date" : "20…

「公 告」根据中华人民共和国法律,Bing 在中国内地暂停 “搜索自动建议” 功能 30 天。

根据中华人民共和国法律,Bing 中国已经被政府有关部门要求在中国内地暂停 “搜索自动建议” 功能 30 天。作为全球性搜索平台,Bing 将持续致力于尊重法治与用户获取信息的权利,在遵守法律的前提下最大限度地帮助客户寻找所需信息。 Bing Chin…

数据结构---优先级队列(堆)

博主主页: 码农派大星. 数据结构专栏:Java数据结构 关注博主带你了解更多数据结构知识 1. 优先级队列 1.1 概念 前面介绍过队列,队列是一种先进先出(FIFO)的数据结构,但有些情况下,操作的数据可能带有优先级,一般出队 列时&am…

微软Copilot+ PC:Phi-Silica

大模型技术论文不断,每个月总会新增上千篇。本专栏精选论文重点解读,主题还是围绕着行业实践和工程量产。若在某个环节出现卡点,可以回到大模型必备腔调重新阅读。而最新科技(Mamba,xLSTM,KAN)则提供了大模…

Tkinter描述

Tkinter是Python中的一个标准GUI库,使用Tcl/Tk作为底层实现,提供了创建图形用户界面的工具。Tkinter提供了一组标准的GUI元素和布局管理器,帮助开发人员快速构建应用程序。使用Tkinter,可以快速创建简单的GUI应用程序,…

C++入门:从C语言到C++的过渡(2)

目录 1.缺省参数 1.1缺省参数的概念 1.2缺省参数的分类及使用 1.3注意点 2.函数重载 2.1函数重载的定义 2.2函数重载的情况分类 2.3注意 2.4函数名修饰规则 3.引用 3.1引用的概念 3.2注意事项 3.3常引用 4.4引用的使用场景 4.4.1作为函数的参数 4.4.2做函数返回…

【学习笔记】Windows GDI绘图目录

题外话 不知几时开始,觉得学习过程中将内容记录下来,有助于加强记忆,还方便后续查找,顺便帮助有需要的人,更有来自您阅读、点赞、收藏和评论时给我带来的动力与兴奋。 目录 【学习笔记】Windows GDI绘图(一)图形概述…

B站大数据分享视频创作300天100+原创内容4000+粉

以今年五一作为一个里程碑参考点,给明年一个可以比较的数据。 我正经发力创作是2023.06.17 (前面几个视频是试水),300天不到一年时间 创作了100原创数据相关视频,创作频率应该很高了,收获了下面几个数字,审视自身&…

如何建设高效的外贸自建站?

建设高效的外贸自建站,首先要从明确目标和受众开始。了解你的目标市场和潜在客户是关键,这样你可以有针对性地进行设计和内容创作。站点的设计应该简洁明了,导航要方便,确保访客户能够快速找到所需的信息。 而内容是网站的核心。…

Java基础的语法---String

Java的String类是不可变的,意味着一旦创建,其值就不能被改变。String类提供了丰富的API来操作字符串。 以下是一些常用的方法: 构造方法: 有以下几种常见的: public class stringlearn {public static void main(S…

LNWT--篇章二小测

问题1: Transformer中的softmax计算为什么需要除以$d_k$? 为了稳定数值计算和防止梯度消失或爆炸问题 问题2: Transformer中attention score计算时候如何mask掉padding位置? 将掩码矩阵添加到缩放后的注意力分数上。由于我们使用了负无穷,经过softma…

ATmega328P加硬件看门狗MAX824L看门狗

void Reversewdt(){ //硬件喂狗,11PIN接MAX824L芯片WDIif (digitalRead(11) HIGH) {digitalWrite(11, LOW); //低电平} else {digitalWrite(11, HIGH); //高电平 }loop增加喂狗调用 void loop() { …… Reversewdt();//喂狗 }

从0到1!得物如何打造通用大模型训练和推理平台

1.背景 近期,GPT大模型的发布给自然语言处理(NLP)领域带来了令人震撼的体验。随着这一事件的发生,一系列开源大模型也迅速崛起。依据一些评估机构的评估,这些开源模型大模型的表现也相当不错。一些大模型的评测情况可…

ggml文件格式

ggml文件格式 其中模型文件使用 ggml/examples/gpt-2/download-model.sh 脚本下载 我下载的是gpt-2 117M 这个 模型词汇编码表 encoder.json : {"!": 0,"\"": 1,"#": 2,"$": 3,"%": 4,"&":…

佩戴安全头盔监测识别摄像机

佩戴安全头盔是重要的安全措施,尤其在工地、建筑工程和工业生产等领域,安全头盔的佩戴对于工人的生命安全至关重要。为了更好地管理和监控佩戴安全头盔的情况,监测识别摄像机成为了一项重要的工具。监测识别摄像机可以通过智能技术监测并记录…

Java系统学习资料(备忘)

本文记录下一下优秀的Java系统学习的资料: java程序员从小工到专家成神之路(2024版) | 程序那些事 Java技能树