14 个被低估的 Python 库
Python 的流行是无可否认的,而且理由充分——它丰富的库生态,由活跃的开发者社区构建,不断让编码变得更简单、更高效。虽然我们大多数人熟悉 NumPy、Pandas 和 Django 这样的大名,但还有一整个世界的鲜为人知的库,可以让你的编码生活轻松得多。在这篇文章中,我将向你介绍 16 个你可能还没发现、但绝对应该了解的现代 Python 库。无论你是想精简项目还是探索新工具,这些隐藏的瑰宝都值得一看。
"Python 包让曾经复杂的东西变得毫不费力地简单。"
1. PyScript
"在浏览器里运行 Python——无需后端!"
如果 Python 和 Web 生了孩子,那它看起来就像 PyScript。这是一个创新包,允许你使用 WebAssembly 直接在浏览器里编写和运行 Python 代码。它构建在 Pyodide 之上,弥合了前端 Web 开发与 Python 之间的鸿沟,让开发者无需碰 JavaScript 就能构建丰富、交互式的 Web 应用。
主要特性:-
- 简单:你的应用在浏览器里运行,无需复杂的安装。
- 富有表现力:用 Python 这样强大、流行且易学的语言创建应用。
- 可扩展:不需要昂贵的基础设施~你的代码运行在你用户的浏览器里。
- 可分享:应用只是 Web 上的一个 URL。仅此而已!
- 通用:你的代码可以在任何运行浏览器的地方运行……也就是任何地方!
- 安全:PyScript 运行在世界上最久经考验的计算平台上——浏览器!
- 强大:Web 和 Python 的精华,终于结合在了一起。
最棒的是,无需安装 PyScript;你只需要把它包含在你的 HTML 代码里。
<head>
<link rel="stylesheet" href="https://pyscript.net/releases/2025.2.4/core.css">
<script type="module" src="https://pyscript.net/releases/2025.2.4/core.js"></script>
</head>
这里有一些真实世界的示例,你可以在这里和这里探索。你可以通过官方文档了解更多这个库的信息:PyScript 文档
2. Polars
"重新定义 Python 速度的极速 DataFrame 库!"
Polars 是一个用于处理大型数据集的高性能 DataFrame 库,用 Rust 构建,旨在提供速度和可扩展性。它尤其以并行执行能力著称,是数据处理中比 pandas 更快的替代方案。
Polars 是适应现代数据处理需求的库,为大规模数据任务提供无与伦比的性能和响应能力。
主要特性:
- 速度:通过并行执行和优化算法提供闪电般的性能。
- 多线程:设计为充分利用多核处理器,使操作更快。
- 基于 Rust:用 Rust 构建,实现高效的内存管理和性能。
- 惰性执行:支持惰性求值,通过推迟计算直到需要结果来优化查询。
- 内置 Arrow 支持:Polars 与 Apache Arrow 无缝集成,实现高效的列式数据操作。
- Python 和 Rust API:提供易用的 Python 绑定,并可扩展到 Rust 以进行更高级的优化。
import polars as pl
# Load the Titanic dataset lazily
q = (
pl.scan_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv")
.filter((pl.col("Survived") == 1) & (pl.col("Age") > 0) & (pl.col("Fare") > 0)) # Filter valid ages and fares
.with_columns(
(pl.col("Fare") / pl.col("Age")).alias("fare_per_year") # Derived metric
)
.group_by("Pclass")
.agg([
pl.col("Age").mean().alias("avg_age"),
pl.col("Fare").sum().alias("total_fare"),
pl.col("Survived").mean().alias("survival_rate"), # Survival rate per class
pl.col("fare_per_year").mean().alias("avg_fare_per_year")
])
.sort("total_fare", descending=True) # Sort by total fare paid
)
df = q.collect()
print(df)
应用场景:
- 大数据处理:适合处理无法装入内存的大型数据集。
- 数据分析:对寻找快速高效方式进行复杂数据操作的分析师很有用。
- 机器学习:凭借其速度和内存效率,可用于预处理和特征工程。
你可以从它的官方文档了解更多这个包的信息。
3. Ruff
"你需要的史上最快的 linter!"
Ruff 是一个快速、现代的 Python linter 和代码格式化器,用 Rust 构建,能高效检测和纠正 Python 中的常见编码问题。
主要特性
- 运行速度比 flake8 这样的传统 linter 和 Black 这样的格式化器快 10–100 倍。
- 通过跳过未更改的文件避免冗余分析。
- 支持自动纠正常见错误。
- 提供 800+ 条内置规则,包括对流行的 flake8 插件(如 flake8-bugbear)的原生实现。
- 轻松与 VS Code 和其他开发环境配合使用。
Ruff 可以用来替代 Flake8(外加几十个插件)、Black、isort、pydocstyle、pyupgrade、autoflake 等等,而且执行代码的速度比任何单一工具都快几十倍甚至几百倍。
# Install Ruff
pip install ruff
# Run Ruff on a Python project
ruff path/to/your/project
让我们用一个装满劣质代码的测试目录来看看它的表现。
你知道吗?? 你甚至可以请 Ruff 修复你项目里的问题。 听起来很棒,对吧?? 让我们也试试……
你可以从它们的官方文档了解更多这个包的信息。
4. Pandera
"在坏数据抓住你之前抓住它。"
Pandera 是一个统计数据验证库,让你能为 pandas(现在是 Polars)DataFrame 定义 schema。把它想象成数据验证遇上类型检查——你指定数据应该是什么样,Pandera 确保它在流经你的流水线之前符合要求。
主要特性:
- 支持 pandas 和 polars:与两个流行的 DataFrame 库都能配合。
- 自定义检查:用简单的 Python 函数创建复杂的自定义验证逻辑。
- 类型安全的装饰器:用 DataFrame schema 注解函数,确保输入/输出被验证。
- Hypothesis 集成:生成合成测试数据,用于稳健的单元测试。
import pandas as pd
import pandera as pa
from pandera import Column, DataFrameSchema, Check
# Simulate Titanic dataset (subset of columns)
df = pd.DataFrame({
"PassengerId": [1, 2, 3],
"Pclass": [3, 1, 3],
"Name": ["Braund, Mr. Owen Harris", "Cumings, Mrs. John Bradley", "Heikkinen, Miss. Laina"],
"Age": [22, 38, -26], ## Negative Age Passed
"Survived": [0, 1, 1],
})
# Define schema with realistic constraints
schema = DataFrameSchema({
"PassengerId": Column(int, Check.greater_than(0)),
"Pclass": Column(int, Check.isin([1, 2, 3])), # Only valid passenger classes
"Name": Column(str, Check.str_length(min_value=3)),
"Age": Column(int, Check.ge(0)), # Age can't be negative
"Survived": Column(int, Check.isin([0, 1])) # Must be binary
})
# Validate the DataFrame
validated_df = schema.validate(df)
print(validated_df)
应用场景:
- ETL 验证:在摄取点捕获数据问题。
- ML 流水线:确保训练数据与生产环境中使用的格式匹配。
- 分析质量保证:在生成报告或仪表盘之前验证数据假设。
5. Jax
"打了兴奋剂的 NumPy,高性能机器学习。"
JAX 是一个高性能数值计算库,把自动微分和 GPU/TPU 加速带给标准的 NumPy 代码。凭借其简单性、速度以及与现代化硬件的深度集成,它被广泛用于研究和生产级机器学习系统。
主要特性
- 使用
autograd提供快速高效的梯度计算,非常适合深度学习和优化任务。 - 通过使用
XLA编译 Python 代码来加速计算,在 CPU、GPU 和 TPU 上优化执行。 vmap函数简化了批量计算的编写,无需手动循环。- 通过
pmap支持多设备执行,实现跨多个加速器的可扩展训练。 - 提供类似 NumPy 的 API 和增强性能,让 NumPy 用户平滑过渡。
import jax.numpy as jnp
from jax import grad, jit
# Define a simple function
def loss_fn(x):
return jnp.sum((x - 3) ** 2)
# Get the gradient of the function
grad_loss = grad(loss_fn)
# Compile for speed
jit_grad_loss = jit(grad_loss)
x = jnp.array([1.0, 2.0, 3.0])
print(jit_grad_loss(x)) ## [-4. -2. 0.]
你可以通过官方文档了解更多这个包的信息:JAX 官方文档
6. Textual
"用纯 Python 构建感觉像 GUI 的现代 TUI 应用。"
Textual 是一个面向 Python 的下一代 TUI(文本用户界面)框架,让你直接在终端里构建交互式、现代、响应式的应用。凭借类似 React 的组件系统、热重载和类似 CSS 的样式,它为终端应用带来了前端 Web 开发的氛围。
主要特性
- 使用组件和状态更新创建动态 UI。
- 由
rich库驱动,实现漂亮的格式化、表格、图表等。 - 无需离开命令行就能构建类似桌面的应用。
- 用熟悉的声明式语法为你的 UI 设置样式。
- Flexbox 式布局,用于响应式地排列组件。
from textual.app import App, ComposeResult
from textual.widgets import Button, Header, Footer, Static
from textual.containers import Vertical
import pyjokes
class JokeApp(App):
CSS_PATH = None # You can style with CSS if needed
BINDINGS = [("q", "quit", "Quit")]
def compose(self) -> ComposeResult:
yield Header()
with Vertical():
self.joke_display = Static("Click the button for a joke!")
yield self.joke_display
yield Button("Tell me a joke!", id="joke-button")
yield Footer()
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "joke-button":
joke = pyjokes.get_joke()
self.joke_display.update(joke)
if __name__ == "__main__":
import sys
try:
import pyjokes
except ImportError:
print("Installing pyjokes...")
import subprocess
subprocess.check_call([sys.executable, "-m", "pip", "install", "pyjokes"])
JokeApp().run()
要退出应用,请按键盘上的 'q' 键。
你可以通过Real Python的文章了解更多这个库的信息。
7. Optuna
"又快又省力的超参数调优。"
Optuna 是一个面向机器学习的自动超参数优化框架。它专为灵活性、速度和效率而设计,智能地搜索超参数空间,用最少的样板代码为你的模型找到最佳配置。
主要特性
- 与 scikit-learn、PyTorch、XGBoost、LightGBM 等无缝协作。
- 使用树结构 Parzen 估计器(TPE)和多变量算法。
- 内置提前停止以节省计算时间。
- 在 CPU、GPU 或集群上运行研究(study)。
- 通过重要性图、参数关系等获得洞察。
- 把目标函数定义为纯 Python 函数——无需配置文件。
- 与 Optuna Dashboard 集成,实时可视化试验、指标和收敛情况。
import optuna
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
def objective(trial):
n_estimators = trial.suggest_int("n_estimators", 10, 200)
max_depth = trial.suggest_int("max_depth", 2, 32)
clf = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth)
iris = load_iris()
return cross_val_score(clf, iris.data, iris.target, cv=3).mean()
study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=50)
print("Best trial:", study.best_trial)
下面是上述代码将生成的输出日志。
[I 2025-05-04 16:25:50,435] A new study created in memory with name: no-name-9ea9687d-ef0c-4af6-b587-2e614ce9a4f8
[I 2025-05-04 16:25:52,387] Trial 0 finished with value: 0.96 and parameters: {'n_estimators': 169, 'max_depth': 22}. Best is trial 0 with value: 0.96.
[I 2025-05-04 16:25:52,621] Trial 1 finished with value: 0.96 and parameters: {'n_estimators': 16, 'max_depth': 7}. Best is trial 0 with value: 0.96.
[I 2025-05-04 16:25:54,186] Trial 2 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 130, 'max_depth': 31}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:25:55,034] Trial 3 finished with value: 0.96 and parameters: {'n_estimators': 69, 'max_depth': 2}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:25:56,309] Trial 4 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 105, 'max_depth': 24}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:25:59,281] Trial 5 finished with value: 0.96 and parameters: {'n_estimators': 174, 'max_depth': 22}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:03,159] Trial 6 finished with value: 0.9466666666666667 and parameters: {'n_estimators': 183, 'max_depth': 2}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:04,163] Trial 7 finished with value: 0.96 and parameters: {'n_estimators': 79, 'max_depth': 6}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:06,322] Trial 8 finished with value: 0.96 and parameters: {'n_estimators': 170, 'max_depth': 15}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:07,704] Trial 9 finished with value: 0.96 and parameters: {'n_estimators': 137, 'max_depth': 19}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:09,256] Trial 10 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 128, 'max_depth': 32}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:11,150] Trial 11 finished with value: 0.96 and parameters: {'n_estimators': 118, 'max_depth': 32}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:13,406] Trial 12 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 139, 'max_depth': 32}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:15,424] Trial 13 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 85, 'max_depth': 28}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:16,547] Trial 14 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 141, 'max_depth': 28}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:16,806] Trial 15 finished with value: 0.96 and parameters: {'n_estimators': 50, 'max_depth': 27}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:17,422] Trial 16 finished with value: 0.96 and parameters: {'n_estimators': 119, 'max_depth': 12}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:18,411] Trial 17 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 200, 'max_depth': 32}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:18,937] Trial 18 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 104, 'max_depth': 26}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:19,707] Trial 19 finished with value: 0.96 and parameters: {'n_estimators': 153, 'max_depth': 16}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:19,938] Trial 20 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 42, 'max_depth': 19}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:20,622] Trial 21 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 133, 'max_depth': 30}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:21,362] Trial 22 finished with value: 0.96 and parameters: {'n_estimators': 149, 'max_depth': 32}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:21,972] Trial 23 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 121, 'max_depth': 29}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:22,757] Trial 24 finished with value: 0.96 and parameters: {'n_estimators': 154, 'max_depth': 25}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:23,228] Trial 25 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 93, 'max_depth': 31}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:23,862] Trial 26 finished with value: 0.96 and parameters: {'n_estimators': 125, 'max_depth': 29}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:24,657] Trial 27 finished with value: 0.96 and parameters: {'n_estimators': 159, 'max_depth': 23}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:25,177] Trial 28 finished with value: 0.96 and parameters: {'n_estimators': 101, 'max_depth': 26}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:26,374] Trial 29 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 193, 'max_depth': 20}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:27,486] Trial 30 finished with value: 0.96 and parameters: {'n_estimators': 134, 'max_depth': 30}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:28,235] Trial 31 finished with value: 0.96 and parameters: {'n_estimators': 84, 'max_depth': 28}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:28,708] Trial 32 finished with value: 0.96 and parameters: {'n_estimators': 63, 'max_depth': 30}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:29,292] Trial 33 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 110, 'max_depth': 32}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:29,371] Trial 34 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 10, 'max_depth': 27}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:29,809] Trial 35 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 87, 'max_depth': 25}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:30,234] Trial 36 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 68, 'max_depth': 11}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:30,920] Trial 37 finished with value: 0.96 and parameters: {'n_estimators': 145, 'max_depth': 21}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:31,110] Trial 38 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 29, 'max_depth': 24}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:31,891] Trial 39 finished with value: 0.96 and parameters: {'n_estimators': 165, 'max_depth': 30}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:32,562] Trial 40 finished with value: 0.96 and parameters: {'n_estimators': 129, 'max_depth': 29}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:33,487] Trial 41 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 184, 'max_depth': 31}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:34,469] Trial 42 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 199, 'max_depth': 32}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:35,007] Trial 43 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 111, 'max_depth': 28}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:35,882] Trial 44 finished with value: 0.96 and parameters: {'n_estimators': 181, 'max_depth': 32}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:36,304] Trial 45 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 75, 'max_depth': 27}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:36,970] Trial 46 finished with value: 0.9666666666666667 and parameters: {'n_estimators': 140, 'max_depth': 31}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:37,480] Trial 47 finished with value: 0.96 and parameters: {'n_estimators': 94, 'max_depth': 29}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:38,046] Trial 48 finished with value: 0.96 and parameters: {'n_estimators': 112, 'max_depth': 14}. Best is trial 2 with value: 0.9666666666666667.
[I 2025-05-04 16:26:39,151] Trial 49 finished with value: 0.9533333333333333 and parameters: {'n_estimators': 175, 'max_depth': 3}. Best is trial 2 with value: 0.9666666666666667.
**Best trial: FrozenTrial(number=2, state=1, values=[0.9666666666666667], datetime_start=datetime.datetime(2025, 5, 4, 16, 25, 52, 626111), datetime_complete=datetime.datetime(2025, 5, 4, 16, 25, 54, 186243), params={'n_estimators': 130, 'max_depth': 31}, user_attrs={}, system_attrs={}, intermediate_values={}, distributions={'n_estimators': IntDistribution(high=200, log=False, low=10, step=1), 'max_depth': IntDistribution(high=32, log=False, low=2, step=1)}, trial_id=2, value=None)**
Optuna 帮助为推荐系统、NLP 模型和预测任务找到最佳配置,确保最优性能。它还支持 AutoML 工作流,自动化模型选择和调优。在强化学习中,Optuna 微调智能体参数以提高决策效率。
8. Dask
*"把 Python 工作流从笔记本扩展到集群——无需重写。"
Dask 是一个面向 Python 的并行计算框架,把整个 PyData 技术栈——包括 pandas、NumPy、scikit-learn 等——从单机扩展到分布式集群。无论你是在处理大型数据集还是执行复杂计算,Dask 都能让你以最小的代码改动高效地完成。
主要特性
- pandas、NumPy 和 scikit-learn 的即插即用替代品。
- 从本地线程无缝扩展到基于云的分布式系统。
- 支持惰性执行。
- 使用装饰器或原生 Dask API 并行化函数。
- 实时可视化任务图、内存使用和进度。
- 与 CSV、Parquet、HDF5 等现有数据格式配合使用。
让我们使用著名的大规模"黄色出租车行程数据",用 Dask 做一些基本分析。
import dask.dataframe as dd
import matplotlib.pyplot as plt
import seaborn as sns
# Load large CSV file (e.g., 1.6GB taxi trip dataset)
df = dd.read_csv("https://raw.githubusercontent.com/Azure/config-driven-data-pipeline/main/example/data/nyc-taxi/yellow_tripdata_2020-09.csv", assume_missing=True)
# Clean and prepare: filter out negative fares or zero distances
df_clean = df[(df["fare_amount"] > 0) & (df["trip_distance"] > 0)]
# Calculate mean fare per mile
df_clean["fare_per_mile"] = df_clean["fare_amount"] / df_clean["trip_distance"]
# Group by passenger count and compute average fare per mile
fare_by_passenger = df_clean.groupby("passenger_count")["fare_per_mile"].mean().compute()
# Visualize results
sns.barplot(x=fare_by_passenger.index, y=fare_by_passenger.values)
plt.xlabel("Passenger Count")
plt.ylabel("Average Fare per Mile")
plt.title("Fare Efficiency by Passenger Count")
plt.show()
在这里抢先一瞥更多与 Dask 相关的示例。
"简单是终极的复杂。" — 列奥纳多·达·芬奇
下一个包让你无需臃肿就能构建快速、可扩展的 API——只关注重要的东西。
9. Robyn
"用 Python 和异步魔法构建闪电般快速的 Web API。"
Robyn 是一个现代、高性能的 Web 框架,用于在 Python 中构建异步 API。它被设计得简单直观,构建在 asyncio 和 Python 的异步特性之上,为处理高请求量提供了非凡的速度和并发性。
主要特性
- 构建在 Python 的 async/await 之上,用于并发处理许多请求。
- 作为 API,比大多数传统 Python Web 框架(如 Flask 或 Django)性能更好。
- 干净易用的路由系统,满足大多数 API 需求。
- 原生支持标准 HTTP 方法和 JSON 响应。
- 无缝集成 WebSockets,实现实时通信。
- 针对以最小开销处理 JSON 载荷进行了优化。
- 非常适合低延迟应用和微服务。
- 轻松添加中间件,用于认证、日志记录等。
你可以通过浏览他们的 GitHub 仓库了解更多这个库的信息,这个仓库维护得很好、写得也好:Robyn GitHub
10. HTTPX
*"让你的 HTTP 请求快速而现代——同时支持异步和同步。"
HTTPX 是一个功能完备的 Python HTTP 客户端,同时支持同步和异步操作,为经典的 requests 库提供了一个快速、现代的替代方案。凭借对 HTTP/2、连接池等的支持,它非常适合高性能应用和微服务。
主要特性
- 既能处理传统的阻塞代码,也能处理现代的 async/await 代码。
- 通过在单个连接上多路复用多个请求来优化更快地请求。
- 复用连接以使请求更快并减少开销。
- 包含自动证书验证和安全连接。
- 轻松配置 HTTP 代理或自定义网络设置。
让我们利用 HTTPX Python 库,从开源的 QuotestoScrape 网站抓取所有精彩的语录。
import httpx
from bs4 import BeautifulSoup
import asyncio
# URL to scrape
url = 'https://quotes.toscrape.com/'
# Asynchronous function to scrape quotes
async def scrape_quotes():
async with httpx.AsyncClient() as client:
response = await client.get(url)
# Parse the HTML content with BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
# Find all quote blocks on the page
quotes = soup.find_all('div', class_='quote')
# Loop through each quote and extract the text and author
for quote in quotes:
text = quote.find('span', class_='text').get_text()
author = quote.find('small', class_='author').get_text()
print(f'"{text}" - {author}')
# Run the asynchronous function
async def main():
await scrape_quotes()
# Call the main function
if __name__ == "__main__":
asyncio.run(main())
你可以通过阅读这篇文章了解更多这个库的信息。
11. WebView
"非常简单,却非常有效。"
WebView 提供了一种惊人地简单又强大的方式,用熟悉的 Web 技术(如 HTML、CSS 和 JavaScript)创建看起来原生的桌面应用——而且全部来自 Python 内部。
让 WebView 脱颖而出的特性是它的轻量设计和易用性。你不需要深入复杂的框架或学习新的 UI 工具包。相反,你只需几行代码就能在原生 GUI 窗口内渲染你的 Web 内容。
对于想要构建跨平台桌面应用、同时利用现有前端技能的开发者来说,它是一个理想的解决方案。
主要特性
- 跨平台。
- 轻量且快速。
- 易于与 API 集成。
- 完全离线运行。
- 打包简单且完全可定制。
让我们用这个神奇的库构建一个笔记应用 GUI,利用 CSS 和 JS 的力量,全部在我们的桌面环境中完成。
import webview
notes = []
html_content = """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Notes</title>
<style>
body { font-family: sans-serif; background: #f0f4f8; padding: 30px; color: #333; }
h1 { color: #4a90e2; font-size: 2em; margin-bottom: 10px; }
textarea, button { font-size: 1em; border-radius: 6px; }
textarea { width: 100%; height: 100px; padding: 10px; border: 1px solid #ccc; resize: vertical; margin-bottom: 10px; }
button { padding: 10px 15px; border: none; cursor: pointer; margin-right: 5px; }
.add { background: #4caf50; color: white; }
.delete { background: #f44336; color: white; float: right; }
.note { background: #fff; border-left: 5px solid #4a90e2; padding: 10px; margin-top: 10px; border-radius: 6px; border: 1px solid #ddd; }
</style>
</head>
<body>
<h1>📝 My Notes</h1>
<textarea id="note-input" placeholder="Write your note here..."></textarea>
<button class="add" onclick="addNote()">Add Note</button>
<div id="note-list"></div>
<script>
window.onload = () => pywebview.api.get_notes().then(render);
const addNote = () => {
const note = document.getElementById("note-input").value.trim();
if (note) {
pywebview.api.add_note(note).then(render);
document.getElementById("note-input").value = "";
}
};
const deleteNote = i => pywebview.api.delete_note(i).then(render);
const render = notes => document.getElementById("note-list").innerHTML = notes.map(
(n, i) => `<div class="note">${n}<button class="delete" onclick="deleteNote(${i})">X</button></div>`
).join('');
</script>
</body>
</html>
"""
class Api:
def get_notes(self): return notes
def add_note(self, text): notes.append(text); return notes
def delete_note(self, index): notes.pop(index); return notes
if __name__ == '__main__':
webview.create_window('Notes App', html=html_content, js_api=Api(), width=500, height=600)
webview.start()
应用场景:
- 内部工具的桌面版(例如,仪表盘、数据录入应用)
- 需要原生访问的混合应用(文件系统、硬件等)。
- 拥有丰富 UI 但简单 Python 后端的教育软件。
想了解更多这个库的信息??看看他们的官方仓库,里面有很多有用的东西。
12. Mimesis
"用于真实测试的真实假数据——不乱糟糟。"
Mimesis 是一个高性能的 Python 假数据生成器,用于生成逼真的虚拟数据,供测试、原型制作和数据匿名化使用。与基本的 Faker 库不同,它支持几十种语言环境、领域和数据类型——从个人信息到金融、食品、科学,甚至加密货币。
主要特性
- 支持 30+ 种语言。
- 即插即用的假数据生成器。
- 专为与单元测试、CI 流水线和 mock 框架轻松配合而设计。
- 旨在快速创建海量数据集,非常适合负载测试和模拟。
import pandas as pd
from mimesis import Person, Datetime
from mimesis.enums import Gender
from random import randint, choice
# Initialize providers
person = Person('en')
datetime = Datetime()
# Sample product catalog
product_catalog = [
"Wireless Mouse", "Bluetooth Speaker", "Noise Cancelling Headphones",
"Gaming Keyboard", "USB-C Charger", "Smartwatch", "LED Desk Lamp"
]
# Data dictionary
data = {
'Customer Name': [],
'Email': [],
'Phone': [],
'Product': [],
'Amount ($)': [],
'Purchase Date': []
}
n = 20 # Number of records
for _ in range(n):
data['Customer Name'].append(person.full_name(gender=choice([Gender.MALE, Gender.FEMALE])))
data['Email'].append(person.email())
data['Phone'].append(person.telephone())
data['Product'].append(choice(product_catalog))
data['Amount ($)'].append(round(randint(20, 500) + 0.99, 2))
data['Purchase Date'].append(datetime.date(start=2023, end=2025))
# Create DataFrame
df = pd.DataFrame(data)
# Display the fake dataset
df
你可以通过它的官方文档详细了解这个包。
13. Jellyfish
"让字符串匹配变得简单。"
Jellyfish 是一个强大的 Python 库,旨在提供广泛的字符串比较方法,让你轻松找到字符串之间相似或语音上的匹配。对于精确字符串匹配往往难以实现、而灵活性和近似匹配至关重要的文本处理任务来说,它是一个无价的工具。
主要特性
- 支持各种算法,包括 Levenshtein、Jaro-Winkler 等。
- 提供 Soundex 和 Metaphone 等语音编码方法,用于匹配发音相似的字符串。
- 易于与各种字符串类型和编码格式配合使用。
- 针对速度和最小内存使用进行了优化。
- 简单的 API 集成,用于文本清理、验证和相似度检查。
假设你在多家在线商店管理产品列表,想要匹配"三星 Galaxy S21"这样的产品在不同目录中的变体。利用 jellyfish,你可以用最少的精力和代码做到这一点。
import pandas as pd
import jellyfish
# Catalog 1: List of product names
catalog_1 = [
"Samsung Galaxy S21 5G",
"Apple iPhone 12 Pro Max"
]
# Catalog 2: List of product names (with variations)
catalog_2 = [
"Samsung Galaxy S21 5G - Phantom Black",
"Samsung Galaxy S21 5G - White",
"Apple iPhone 12 Pro Max 128GB",
"iPhone 12 Pro Max by Apple",
"Samsung Galaxy S21 5G - Blue",
"Apple iPhone 12 Pro Max"
]
# Function to compare the similarity of product names using Jaro-Winkler
def check_similarity(name1, name2):
return jellyfish.jaro_winkler_similarity(name1.lower(), name2.lower())
# Create DataFrame to store product comparisons
data = {
'Catalog 1 Product': [],
'Catalog 2 Product': [],
'Jaro-Winkler Similarity': [],
'Match': []
}
# Compare products from both catalogs
for product_1 in catalog_1:
for product_2 in catalog_2:
similarity_score = check_similarity(product_1, product_2)
match_flag = 'Yes' if similarity_score > 0.85 else 'No'
# Append results to data dictionary
data['Catalog 1 Product'].append(product_1)
data['Catalog 2 Product'].append(product_2)
data['Jaro-Winkler Similarity'].append(similarity_score)
data['Match'].append(match_flag)
# Create DataFrame to display the results
df = pd.DataFrame(data)
# Display the resulting DataFrame
df
可以清楚地看到,我们的目录中有一些产品很相似,只是写法不同。你可以用这个把它们合并到同一个节点下,以节省空间并让你的系统更简单。
14. Numerizer
"让你的应用理解数字——不管人类怎么写它们。"
Numerizer 是一个 Python 库,把写出来的数字(比如 "twenty-one thousand five hundred")转换成实际的数字(21500)。它在自然语言处理(NLP)、语音界面或任何用户以书面形式输入数字数据的场景中尤其有用。
主要特性
- 即插即用的文本转数字转换器。
- 处理标点、连词和部分短语。
- 支持很大范围的数字。
- Pythonic 且极简。
- 在把文本喂给 NLP 流水线之前帮助清理文本。
from numerizer import numerize
import pandas as pd
# Simplified sentences
sentences = [
"I have twenty-five apples.",
"He owes me one hundred dollars.",
"Three dozen eggs.",
"Two million dollars.",
"She ran forty kilometers.",
"There are one thousand students.",
"My laptop cost fifteen hundred dollars.",
"We need seven hundred chairs.",
"The vase is worth five thousand euros.",
"It was in nineteen ninety-nine.",
"He read one hundred books.",
"The bill is one hundred dollars.",
"The distance is one hundred miles.",
"They sold three hundred units.",
"The company made five million profit."
]
# Create a DataFrame showing original and numerized sentences
df = pd.DataFrame({
"Original": sentences,
"Numerized": [numerize(sentence) for sentence in sentences]
})
# Display the result
df
你可以通过他们的 GitHub 仓库了解更多这个库的功能:Numerizer GitHub 仓库
原文链接: 14 Underrated Python Libraries I Wish I Knew 5 Years Ago
汇智网翻译整理,转载请标明出处