自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

2025 最新出爐!15 個(gè) Python 庫(kù)帶你飛

開(kāi)發(fā) 開(kāi)發(fā)工具
在Python的技術(shù)生態(tài)中,豐富多樣的庫(kù)是其一大亮點(diǎn),這些出色的庫(kù)大大拓展了Python的應(yīng)用邊界,堪稱改變編程格局的“利器”。當(dāng)下,技術(shù)迭代日新月異,若想在2025年的編程領(lǐng)域中搶占先機(jī),有幾款極具變革性的現(xiàn)代庫(kù)不容錯(cuò)過(guò)。

在Python的技術(shù)生態(tài)中,豐富多樣的庫(kù)是其一大亮點(diǎn),這些出色的庫(kù)大大拓展了Python的應(yīng)用邊界,堪稱改變編程格局的“利器”。當(dāng)下,技術(shù)迭代日新月異,若想在2025年的編程領(lǐng)域中搶占先機(jī),有幾款極具變革性的現(xiàn)代庫(kù)不容錯(cuò)過(guò)。

1.Polars——極速數(shù)據(jù)幀庫(kù)

Polars是用Rust編寫的超快速數(shù)據(jù)幀庫(kù),用于處理結(jié)構(gòu)化數(shù)據(jù)。

圖片圖片

優(yōu)勢(shì):Polars比Pandas快10到100倍。支持對(duì)大型數(shù)據(jù)集進(jìn)行延遲求值,并且能與Apache Arrow原生協(xié)作。

文檔:https://docs.pola.rs/

安裝

pip install polars

示例:以下是使用Polars創(chuàng)建數(shù)據(jù)幀的簡(jiǎn)單示例:

import polars as pl
import datetime as dt

df = pl.DataFrame(
    {
        "name": ["Alice Archer", "Ben Brown", "Chloe Cooper", "Daniel Donovan"],
        "birthdate": [
            dt.date(1997, 1, 10),
            dt.date(1985, 2, 15),
            dt.date(1983, 3, 22),
            dt.date(1981, 4, 30),
        ],
        "weight": [57.9, 72.5, 53.6, 83.1],  # (kg)
        "height": [1.56, 1.77, 1.65, 1.75],  # (m)
    }
)
print(df)

輸出結(jié)果:

shape: (4, 4)
┌────────────────┬────────────┬────────┬────────┐
│ name           ┆ birthdate  ┆ weight ┆ height │
│ ---            ┆ ---        ┆ ---    ┆ ---    │
│ str            ┆ date       ┆ f64    ┆ f64    │
╞════════════════╪════════════╪════════╪════════╡
│ Alice Archer   ┆ 1997-01-10 ┆ 57.9   ┆ 1.56   │
│ Ben Brown      ┆ 1985-02-15 ┆ 72.5   ┆ 1.77   │
│ Chloe Cooper   ┆ 1983-03-22 ┆ 53.6   ┆ 1.65   │
│ Daniel Donovan ┆ 1981-04-30 ┆ 83.1   ┆ 1.75   │
└────────────────┴────────────┴────────┴────────┘

2.Ruff——最快的Python格式化和代碼檢查工具

Ruff是基于 Rust 語(yǔ)言編寫的超快速代碼檢查工具,其設(shè)計(jì)初衷便是憑借自身強(qiáng)大功能,以 “一器之力” 取代 Flake8、Black 和 isort 這幾款傳統(tǒng)工具,為開(kāi)發(fā)者提供更高效、便捷的代碼檢查與格式化解決方案 。

圖片圖片

優(yōu)勢(shì):它比Flake8快20倍,支持自動(dòng)修復(fù)問(wèn)題,兼具格式化和代碼檢查功能。

文檔:https://docs.astral.sh/ruff/

安裝

pip install ruff

示例:我們可以使用uv初始化一個(gè)項(xiàng)目:

uv init --lib demo

這條命令會(huì)創(chuàng)建一個(gè)具有以下結(jié)構(gòu)的Python項(xiàng)目:

demo
├── README.md
├── pyproject.toml
└── src
    └── demo
        ├── __init__.py
        └── py.typed

然后,將src/demo/__init__.py的內(nèi)容替換為以下代碼:

from typing import Iterable
import os

def sum_even_numbers(numbers: Iterable[int]) -> int:
    """給定一個(gè)整數(shù)的可迭代對(duì)象,返回其中所有偶數(shù)的和。"""
    return sum(
        num for num in numbers
        if num % 2 == 0
    )

接下來(lái),將Ruff添加到項(xiàng)目中:

uv add --dev ruff

然后,可以通過(guò)uv run ruff check在項(xiàng)目上運(yùn)行Ruff代碼檢查:

$ uv run ruff check
src/numbers/__init__.py:3:8: F401 [*] `os` imported but unused
Found 1 error.
[*] 1 fixable with the `--fix` option.

通過(guò)運(yùn)行ruff check --fix自動(dòng)解決這個(gè)問(wèn)題:

$ uv run ruff check --fix
Found 1 error (1 fixed, 0 remaining).

3.PyScript——在瀏覽器中運(yùn)行Python

PyScript讓開(kāi)發(fā)者可以在瀏覽器中編寫和執(zhí)行Python代碼,類似于JavaScript。

優(yōu)勢(shì):PyScript支持開(kāi)發(fā)基于Python的網(wǎng)頁(yè)應(yīng)用,可直接在HTML中使用,無(wú)需后端。

文檔:https://docs.pyscript.net/2025.2.4/

安裝:無(wú)需安裝PyScript,只需在HTML文檔的<head>標(biāo)簽中添加一個(gè)<script>和鏈接標(biāo)簽即可。

<!-- PyScript CSS -->
<link rel="stylesheet" >
<!-- 此腳本標(biāo)簽用于啟動(dòng)PyScript -->
<script type="module" src="https://pyscript.net/releases/2025.2.4/core.js"></script>

示例:創(chuàng)建一個(gè)簡(jiǎn)單的.html文件,并使用<py-script>標(biāo)簽編寫Python代碼。

<!doctype html>
<html>
<head>
    <!-- 推薦的元標(biāo)簽 -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <!-- PyScript CSS -->
    <link rel="stylesheet" >
    <!-- 此腳本標(biāo)簽用于啟動(dòng)PyScript -->
    <script type="module" src="https://pyscript.net/releases/2025.2.4/core.js"></script>
</head>
<body>
    <!-- 現(xiàn)在可以使用<py-script>標(biāo)簽在其中編寫Python代碼 -->
    <py-script>
        import sys
        from pyscript import display

        display(sys.version)
    </py-script>
</body>
</html>

4.Pandera——用于Pandas的數(shù)據(jù)驗(yàn)證工具

Pandera通過(guò)基于模式的驗(yàn)證方式,幫助驗(yàn)證Pandas的數(shù)據(jù)幀(DataFrames)和序列(Series)。

圖片圖片

優(yōu)勢(shì):Pandera可以在數(shù)據(jù)處理前捕獲數(shù)據(jù)錯(cuò)誤,工作方式類似于Pydantic,但專為Pandas設(shè)計(jì),并且支持對(duì)數(shù)據(jù)進(jìn)行單元測(cè)試!

文檔:https://pandera.readthedocs.io/en/stable/

安裝

pip install pandera

示例

import pandas as pd
import pandera as pa

# 待驗(yàn)證的數(shù)據(jù)
df = pd.DataFrame({
    "column1": [1, 4, 0, 10, 9],
    "column2": [-1.3, -1.4, -2.9, -10.1, -20.4],
    "column3": ["value_1", "value_2", "value_3", "value_2", "value_1"],
})
# 定義模式
schema = pa.DataFrameSchema({
    "column1": pa.Column(int, checks=pa.Check.le(10)),
    "column2": pa.Column(float, checks=pa.Check.lt(-1.2)),
    "column3": pa.Column(str, checks=[
        pa.Check.str_startswith("value_"),
        # 定義自定義檢查函數(shù),該函數(shù)接受一個(gè)序列作為輸入,并輸出布爾值或布爾序列
        pa.Check(lambda s: s.str.split("_", expand=True).shape[1] == 2)
    ]),
})
validated_df = schema(df)
print(validated_df)

輸出結(jié)果:

column1  column2  column3
0        1     -1.3  value_1
1        4     -1.4  value_2
2        0     -2.9  value_3
3       10    -10.1  value_2
4        9    -20.4  value_1

5.Textual——用Python構(gòu)建終端用戶界面應(yīng)用程序

Textual允許開(kāi)發(fā)者使用豐富的組件,用Python構(gòu)建現(xiàn)代化的終端用戶界面(TUI)應(yīng)用程序。

優(yōu)勢(shì):用于創(chuàng)建美觀的終端應(yīng)用程序,可與Rich庫(kù)配合進(jìn)行樣式設(shè)置,無(wú)需前端開(kāi)發(fā)經(jīng)驗(yàn)。

文檔:https://textual.textualize.io/tutorial/

安裝

pip install textual

示例:創(chuàng)建TUI應(yīng)用程序的簡(jiǎn)單示例。

from textual.app import App, ComposeResult
from textual.widgets import Label, Button

class QuestionApp(App[str]):
    def compose(self) -> ComposeResult:
        yield Label("Do you love Textual?")
        yield Button("Yes", id="yes", variant="primary")
        yield Button("No", id="no", variant="error")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        self.exit(event.button.id)

if __name__ == "__main__":
    app = QuestionApp()
    reply = app.run()
    print(reply)

運(yùn)行此應(yīng)用程序?qū)⒌玫揭韵陆Y(jié)果:

圖片圖片

6.LlamaIndex——構(gòu)建定制AI助手

LlamaIndex簡(jiǎn)化了為基于大語(yǔ)言模型(LLM)的應(yīng)用程序?qū)Υ笮蛿?shù)據(jù)集進(jìn)行索引和查詢的過(guò)程。

優(yōu)勢(shì):LlamaIndex用于檢索增強(qiáng)生成(RAG),可與OpenAI的GPT模型協(xié)同工作,并且能夠處理結(jié)構(gòu)化和非結(jié)構(gòu)化數(shù)據(jù)。

文檔:https://docs.llamaindex.ai/en/stable/#getting-started

安裝

pip install llama-index

示例:讓我們從一個(gè)簡(jiǎn)單示例開(kāi)始,使用一個(gè)可以通過(guò)調(diào)用工具進(jìn)行基本乘法運(yùn)算的智能體。創(chuàng)建名為starter.py的文件:

  • 設(shè)置一個(gè)名為OPENAI_API_KEY的環(huán)境變量,并賦予其OpenAI API密鑰。
import asyncio
from llama_index.core.agent.workflow import AgentWorkflow
from llama_index.llms.openai import OpenAI

# 定義一個(gè)簡(jiǎn)單的計(jì)算器工具
def multiply(a: float, b: float) -> float:
    """用于將兩個(gè)數(shù)相乘。"""
    return a * b

# 使用我們的計(jì)算器工具創(chuàng)建一個(gè)智能體工作流
agent = AgentWorkflow.from_tools_or_functions(
    [multiply],
    llm=OpenAI(model="gpt-4o-mini"),
    system_prompt="You are a helpful assistant that can multiply two numbers.",
)

asyncdef main():
    # 運(yùn)行智能體
    response = await agent.run("What is 1234 * 4567?")
    print(str(response))

# 運(yùn)行智能體
if __name__ == "__main__":
    asyncio.run(main())

運(yùn)算結(jié)果:1234×4567的結(jié)果是5,678,678。

7.Robyn——最快的Python Web框架

Robyn是Flask和FastAPI的高性能替代框架,針對(duì)多核處理進(jìn)行了優(yōu)化。

圖片圖片

優(yōu)勢(shì): Robyn比FastAPI快5倍。支持異步和多線程,并且借助Rust提升速度。

文檔:https://robyn.tech/documentation/en

安裝

pip install robyn

示例:使用以下命令創(chuàng)建一個(gè)簡(jiǎn)單的項(xiàng)目:

$ python -m robyn --create

產(chǎn)生以下輸出:

$ python3 -m robyn --create
? Directory Path:.
? Need Docker? (Y/N) Y
? Please select project type (Mongo/Postgres/Sqlalchemy/Prisma):
? No DB
  Sqlite
  Postgres
  MongoDB
  SqlAlchemy
  Prisma

這會(huì)創(chuàng)建一個(gè)具有以下結(jié)構(gòu)的新應(yīng)用程序:

├── src
│   ├── app.py
├── Dockerfile

現(xiàn)在你可以在app.py文件中編寫代碼:

from robyn import Request

@app.get("/")
async def h(request: Request) -> str:
    return "Hello, world"

可以使用以下命令運(yùn)行服務(wù)器:

python -m robyn app.py

8.DuckDB——閃電般快速的內(nèi)存數(shù)據(jù)庫(kù)

DuckDB是一個(gè)內(nèi)存中的SQL數(shù)據(jù)庫(kù),在分析方面比SQLite更快。

圖片圖片

優(yōu)勢(shì):在分析方面速度極快,無(wú)需服務(wù)器即可運(yùn)行,并且能輕松與Pandas和Polars集成。

文檔:https://duckdb.org/docs/stable/clients/python/overview.html

安裝

pip install duckdb --upgrade

示例:使用pandas數(shù)據(jù)幀的簡(jiǎn)單示例:

import duckdb
import pandas as pd

pandas_df = pd.DataFrame({"a": [42]})
duckdb.sql("SELECT * FROM pandas_df")

輸出結(jié)果:

┌───────┐
│   a   │
│ int64 │
├───────┤
│    42 │
└───────┘

9.Django——全棧Web框架

Django是高級(jí)Python Web框架,用于快速構(gòu)建安全、可擴(kuò)展的應(yīng)用程序。

圖片圖片

優(yōu)勢(shì):Django內(nèi)置對(duì)象關(guān)系映射(ORM)、包含身份驗(yàn)證系統(tǒng)、具有可擴(kuò)展性和安全性,還有更多優(yōu)勢(shì)。

文檔:https://docs.djangoproject.com/en/5.2/

安裝

pip install django

示例:創(chuàng)建一個(gè)新的Django項(xiàng)目:

django-admin startproject myproject
cd myproject
python manage.py runserver

你應(yīng)該會(huì)看到應(yīng)用程序在http:127.0.0.1:8000/上運(yùn)行。

10.FastAPI——高性能API框架

FastAPI是個(gè)輕量級(jí)且快速的Python Web框架,用于構(gòu)建支持異步的RESTful API。

圖片圖片

優(yōu)勢(shì):內(nèi)置異步支持、自動(dòng)生成OpenAPI和Swagger UI,并且速度快(基于Starlette和Pydantic構(gòu)建)。

文檔:https://fastapi.tiangolo.com/learn/

安裝

pip install fastapi uvicorn

示例:使用FastAPI創(chuàng)建API的簡(jiǎn)單示例:

# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}

運(yùn)行服務(wù)器:

uvicorn main:app --reload

你應(yīng)該會(huì)看到應(yīng)用程序在http:127.0.0.1:8000/上運(yùn)行。

11.LangChain——人工智能驅(qū)動(dòng)的應(yīng)用框架

LangChain是Python框架,簡(jiǎn)化了與像OpenAI的GPT這樣的大語(yǔ)言模型(LLM)的協(xié)作過(guò)程。

圖片

優(yōu)勢(shì):LangChain可以與OpenAI、Hugging Face等集成,將多個(gè)大語(yǔ)言模型調(diào)用鏈接在一起,并且支持基于記憶和檢索的查詢。

文檔:https://python.langchain.com/docs/introduction/

安裝

pip install langchain

示例:使用OpenAI模型創(chuàng)建聊天機(jī)器人的簡(jiǎn)單示例:

pip install -qU "langchain[openai]"
import getpass
import os
from langchain.chat_models import init_chat_model

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

model = init_chat_model("gpt-4o-mini", model_provider="openai")
model.invoke("Hello, world!")

你會(huì)看到聊天機(jī)器人的回復(fù)。

12.Pydantic——數(shù)據(jù)驗(yàn)證與解析

Pydantic通過(guò)Python類型提示實(shí)現(xiàn)數(shù)據(jù)驗(yàn)證,在FastAPI中有著廣泛應(yīng)用。

圖片圖片

優(yōu)勢(shì):Pydantic具備自動(dòng)數(shù)據(jù)驗(yàn)證功能,基于類型提示進(jìn)行數(shù)據(jù)解析,與FastAPI搭配使用效果極佳。

文檔:https://docs.pydantic.dev/latest/

安裝

pip install pydantic

示例

from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int

user = User(name="Aashish Kumar", age=25)
print(user)      # User(name='Aashish Kumar', age=25)
print(user.name) # 'Aashish Kumar'
print(user.age)  # 25

13.Flet——用Python構(gòu)建Web、移動(dòng)和桌面UI

Flet僅使用Python就能構(gòu)建現(xiàn)代化的Web、桌面和移動(dòng)應(yīng)用(無(wú)需HTML/CSS/JS )。

圖片圖片

優(yōu)勢(shì):無(wú)需掌握J(rèn)avaScript或前端知識(shí),可在Web、Windows、macOS和Linux等平臺(tái)使用,是一款響應(yīng)式UI框架。

文檔:https://flet.dev/docs/

安裝

pip install flet

示例:構(gòu)建一個(gè)簡(jiǎn)單的計(jì)數(shù)器應(yīng)用:

import flet
from flet import IconButton, Page, Row, TextField, icons

def main(page: Page):
    page.title = "Flet counter example"
    page.vertical_alignment = "center"
    txt_number = TextField(value="0", text_align="right", width=100)

    def minus_click(e):
        txt_number.value = str(int(txt_number.value) - 1)
        page.update()

    def plus_click(e):
        txt_number.value = str(int(txt_number.value) + 1)
        page.update()

    page.add(
        Row(
            [
                IconButton(icons.REMOVE, on_click=minus_click),
                txt_number,
                IconButton(icons.ADD, on_click=plus_click),
            ],
            alignment="center",
        )
    )

flet.app(target=main)

運(yùn)行程序

python counter.py

應(yīng)用程序?qū)⒃谠僮飨到y(tǒng)窗口中啟動(dòng),這是替代Electron的不錯(cuò)選擇。

圖片圖片

如果想將應(yīng)用作為Web應(yīng)用運(yùn)行,只需將最后一行代碼替換為:

flet.app(target=main, view=flet.AppView.WEB_BROWSER)

再次運(yùn)行,即可立即獲得Web應(yīng)用:

圖片圖片

14.Weaviate——用于AI與搜索的向量數(shù)據(jù)庫(kù)

Weaviate是一款快速的開(kāi)源向量數(shù)據(jù)庫(kù),適用于語(yǔ)義搜索和AI應(yīng)用。

圖片圖片

優(yōu)勢(shì):是人工智能驅(qū)動(dòng)搜索的理想選擇,可存儲(chǔ)文本、圖像和嵌入向量,能應(yīng)對(duì)大規(guī)模數(shù)據(jù)集的需求。

文檔:https://weaviate.io/developers/weaviate

安裝

pip install -U weaviate-client

示例:使用Docker以默認(rèn)設(shè)置運(yùn)行Weaviate,在終端中運(yùn)行以下命令:

docker run -p 8080:8080 -p 50051:50051 cr.weaviate.io/semitechnologies/weaviate:1.29.0

Docker實(shí)例默認(rèn)運(yùn)行在http://localhost:8080。

若要連接到本地實(shí)例且無(wú)需身份驗(yàn)證:

import weaviate

client = weaviate.connect_to_local()
print(client.is_ready())

15.Reflex——用Python構(gòu)建Web應(yīng)用(前端+后端)

Reflex是一個(gè)全棧Web框架,用于使用Python構(gòu)建現(xiàn)代化Web應(yīng)用,與Streamlit類似,但可定制性更強(qiáng)。

圖片圖片

優(yōu)勢(shì):可以用Python構(gòu)建類似React的用戶界面,具備狀態(tài)管理功能,前后端代碼集成在一處。

文檔:https://reflex.dev/docs/getting-started/introduction/

安裝

pip install reflex

示例:使用以下命令創(chuàng)建一個(gè)Reflex項(xiàng)目:

mkdir my_app_name
cd my_app_name
reflex init

創(chuàng)建簡(jiǎn)單應(yīng)用

# app.py
import reflex as rx
import openai

openai_client = openai.OpenAI()

# 后端代碼
class State(rx.State):
    """應(yīng)用程序狀態(tài)。"""
    prompt = ""
    image_url = ""
    processing = False
    complete = False

    def get_image(self):
        """根據(jù)提示獲取圖片。"""
        if self.prompt == "":
            return rx.window_alert("Prompt Empty")
        self.processing, self.complete = True, False
        yield
        response = openai_client.images.generate(
            prompt=self.prompt, n=1, size="1024x1024"
        )
        self.image_url = response.data[0].url
        self.processing, self.complete = False, True

# 前端代碼
def index():
    return rx.center(
        rx.vstack(
            rx.heading("DALL-E", font_size="1.5em"),
            rx.input(
                placeholder="Enter a prompt..",
                on_blur=State.set_prompt,
                width="25em",
            ),
            rx.button(
                "Generate Image", 
                on_click=State.get_image,
                width="25em",
                loading=State.processing
            ),
            rx.cond(
                State.complete,
                rx.image(src=State.image_url, width="20em"),
            ),
            align="center",
        ),
        width="100%",
        height="100vh",
    )

# 將狀態(tài)和頁(yè)面添加到應(yīng)用程序
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")

運(yùn)行開(kāi)發(fā)服務(wù)器

reflex run

你會(huì)看到應(yīng)用在http://localhost:3000運(yùn)行。

NoneNone

責(zé)任編輯:武曉燕 來(lái)源: Python學(xué)研大本營(yíng)
相關(guān)推薦

2015-06-30 10:49:32

2011-04-13 12:20:13

Web服務(wù)器

2023-07-17 10:45:04

模型應(yīng)用

2025-03-27 08:11:17

2021-01-13 11:03:20

Python數(shù)據(jù)代碼

2021-07-19 15:47:45

Python編程語(yǔ)言代碼

2024-08-17 12:14:06

2020-12-16 15:37:19

Python編程語(yǔ)言開(kāi)發(fā)

2025-02-17 11:41:14

2024-12-02 08:00:00

營(yíng)銷聊天機(jī)器人AI

2025-02-13 10:39:23

2024-04-02 10:42:40

Logbook模塊Python開(kāi)發(fā)

2012-07-23 09:15:31

云計(jì)算IaaS最新標(biāo)準(zhǔn)

2022-04-28 10:47:09

漏洞網(wǎng)絡(luò)安全網(wǎng)絡(luò)攻擊

2025-01-09 09:10:39

2019-11-25 15:58:15

Python 3.9新特性模塊

2024-11-06 13:53:55

2021-12-07 09:12:32

Iptables 原理工具

2015-07-06 11:26:29

2018-12-05 09:20:02

MySQL數(shù)據(jù)庫(kù)索引
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)