当前位置: 首页 > 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

相关文章:

  • jenkins升级,涉及ssh remote执行出现Algorithm negotiation fail
  • C++系列-static成员
  • Spring Boot 项目统一异常处理
  • netplan
  • Visual Studio 的调试(一)
  • 42-4 应急响应之文件痕迹排查
  • Rust面试宝典第14题:旋转数组
  • Redis教程(十三):Redis的主从复制模式搭建
  • 【论文阅读】Prompt Fuzzing for Fuzz Driver Generation
  • 设计模式-中介者模式
  • SpringBoot+Mybatis 从头搭建通用管理系统
  • Linux环境下TensorFlow安装教程
  • 简单多状态 dp 问题
  • Facebook广告如何开户以及投放费用?
  • MySQL中创建触发器时,语法与创建存储过程或函数的语法有所不同注意
  • JavaScript-如何实现克隆(clone)函数
  • 收藏网友的 源程序下载网
  • 《Java8实战》-第四章读书笔记(引入流Stream)
  • Android 初级面试者拾遗(前台界面篇)之 Activity 和 Fragment
  • canvas 五子棋游戏
  • const let
  • ESLint简单操作
  • JS创建对象模式及其对象原型链探究(一):Object模式
  • Laravel5.4 Queues队列学习
  • Python爬虫--- 1.3 BS4库的解析器
  • React-Native - 收藏集 - 掘金
  • Spring声明式事务管理之一:五大属性分析
  • Web Storage相关
  • 初识 webpack
  • 从 Android Sample ApiDemos 中学习 android.animation API 的用法
  • 从重复到重用
  • 对象管理器(defineProperty)学习笔记
  • 基于OpenResty的Lua Web框架lor0.0.2预览版发布
  • 看域名解析域名安全对SEO的影响
  • 如何解决微信端直接跳WAP端
  • 推荐一款sublime text 3 支持JSX和es201x 代码格式化的插件
  • 学习笔记DL002:AI、机器学习、表示学习、深度学习,第一次大衰退
  • 怎样选择前端框架
  • 深度学习之轻量级神经网络在TWS蓝牙音频处理器上的部署
  • #HarmonyOS:软件安装window和mac预览Hello World
  • #NOIP 2014#Day.2 T3 解方程
  • #使用清华镜像源 安装/更新 指定版本tensorflow
  • #我与Java虚拟机的故事#连载18:JAVA成长之路
  • (1)bark-ml
  • (Note)C++中的继承方式
  • (PWM呼吸灯)合泰开发板HT66F2390-----点灯大师
  • (WSI分类)WSI分类文献小综述 2024
  • (附源码)ssm基于jsp高校选课系统 毕业设计 291627
  • (蓝桥杯每日一题)love
  • (七)Appdesigner-初步入门及常用组件的使用方法说明
  • (全注解开发)学习Spring-MVC的第三天
  • (四)【Jmeter】 JMeter的界面布局与组件概述
  • (一)、软硬件全开源智能手表,与手机互联,标配多表盘,功能丰富(ZSWatch-Zephyr)
  • (原創) 如何安裝Linux版本的Quartus II? (SOC) (Quartus II) (Linux) (RedHat) (VirtualBox)
  • (原創) 如何使用ISO C++讀寫BMP圖檔? (C/C++) (Image Processing)