小工具知识网

当前位置: 首页 > 行业知识 > 【建议收藏】30个较难Python脚本,纯干货分享

行业知识

【建议收藏】30个较难Python脚本,纯干货分享

2026-10-26 05:29:34 来源:互联网转载

 本篇较难,建议优先学习上篇       ;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, Stringfrom sqlalchemy.orm import sessionmakerfrom 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 nltknltk.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 Flaskfrom 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 BeautifulSoupimport 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_irisfrom sklearn.model_selection import train_test_splitfrom 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 Sequentialfrom 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 snsimport 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

上一篇:pgAdmin,PostgreSQL的驾驭利器,数据库管理从此轻松上手

下一篇:斗鱼怎么绑定服务器直播?