程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

Python标准库中的七个“小众但神奇”的实用函数

balukai 2025-05-14 11:58:29 文章精选 4 ℃

如果你一直在使用Python,想必已经非常熟悉它极其丰富的标准库,这让开发变得高效且直接。虽然像json、datetime、re这样的热门模块经常被关注,但其实还有一批鲜为人知的函数常常被忽视。

本文将讨论这些函数——有些人可能会觉得它们“无用”,但实际上它们一点也不无用!这些功能奇特、非常细分的小众函数可能会让你产生“谁会需要这个?”的疑问。可总有一天,你会遇到它们正好能解决的问题。

所以,让我们来看看这些其实超级有用的函数吧!

GitHub代码链接

  1. textwrap.dedent() —— 轻松整理凌乱的多行字符串

你是否曾在Python中书写多行字符串,却因缩进而感到困扰?如果是这样,textwrap.dedent就是你的好帮手!

看看下面这个示例,使用了textwrap的dedent。它可以移除多行字符串中多余的缩进,让你得到没有前导空格的干净文本。

import textwrap

def my_function():
    # 如果不使用dedent,所有前导空格都会被保留
    description = textwrap.dedent("""
        This is a multi-line string
        that will have consistent indentation
        regardless of how it's indented in the code.
        Pretty neat, right?
    """).strip()

    return description

print(my_function())

输出:

This is a multi-line string
that will have consistent indentation
regardless of how it's indented in the code.
Pretty neat, right?

  1. difflib.get_close_matches() —— 轻松实现模糊字符串匹配

有时你需要查找字符串之间的相似性,或实现“你是不是想找……”的功能。difflib模块的get_close_matches函数正好能帮你实现。

下面的几个例子展示了如何使用该函数:

import difflib

words = ["python", "javascript", "typescript", "ruby", "golang"]
search = "pythn"

matches = difflib.get_close_matches(search, words, n=3, cutoff=0.6)
print(f"Did you mean: {matches}")

输出:

Did you mean: ['python']

第一个例子是在一组编程语言中找到与“pythn”最接近的匹配项。

第二个例子展示了“typescript”的近似匹配既包含“typescript”也包含“javascript”。

search = "typescript"
matches = difflib.get_close_matches(search, words)
print(f"Matches: {matches}")

输出:

['typescript', 'javascript']

这种方法对于命令行工具、搜索功能,或者任何需要处理拼写错误或近似匹配的场景都非常有用。

  1. uuid.uuid4() —— 轻松生成全局唯一ID

如果你需要生成唯一标识符,又不想配置数据库或担心ID冲突,可以使用uuid模块中的相关函数。

下面的代码展示了如何生成一个随机UUID对象,可用作唯一标识符:

import uuid

# 生成一个随机UUID
random_id = uuid.uuid4()
print(f"Unique ID: {random_id}")

输出:

Unique ID: fc4c6638-9707-437b-83a1-76206b5f7191

下面的例子展示了如何将UUID嵌入文件名,以确保其唯一性:

# 以字符串形式用于文件名、数据库键等场景
filename = f"document-{uuid.uuid4()}.pdf"
print(filename)

输出:

document-b5ccbe7a-fad9-4611-8163-be1015c634b9.pdf

这些UUID(通用唯一标识符)几乎可以保证全局唯一——即使跨机器、跨时间也不会重复,非常适合用于文件、数据库条目等需要唯一性的场合。

  1. shutil.get_terminal_size() —— 让CLI应用自适应终端尺寸

想让你的命令行应用根据用户终端的大小自适应?get_terminal_size函数能轻松实现。

用法如下:

import shutil

columns, rows = shutil.get_terminal_size()
print(f"Your terminal is {columns} columns wide and {rows} rows tall")

# 创建一条刚好适合终端宽度的分隔线
print("-" * columns)

输出:

Your terminal is 80 columns wide and 24 rows tall

  1. itertools.groupby() —— 无需字典也能高效分组

需要按某个关键字对数据分组?itertools.groupby()可以高效实现。

这个例子中,我们先按部门对员工列表排序(groupby要求先排序),然后按部门分组打印每位员工。

from itertools import groupby
from operator import itemgetter

# 示例数据: (姓名, 部门)
employees = [
    ("Alice", "Engineering"),
    ("Bob", "Marketing"),
    ("Charlie", "Engineering"),
    ("Diana", "HR"),
    ("Evan", "Marketing"),
]

# 先按部门排序
employees.sort(key=itemgetter(1))

# 按部门分组
for department, group in groupby(employees, key=itemgetter(1)):
    print(f"\n{department} Department:")
    for name, _ in group:
        print(f"  - {name}")

输出:

Engineering Department:

  • Alice
  • Charlie

HR Department:

  • Diana

Marketing Department:

  • Bob
  • Evan
  1. collections.ChainMap —— 无需合并也能多字典查找

需要在多个字典中查找数据?ChainMap让你无需真正合并字典就能按顺序依次查找。

注意:它不是函数,而是collections模块中非常实用的一个类。

实际用例如下:

from collections import ChainMap

defaults = {"theme": "dark", "language": "en", "timeout": 30}
user_settings = {"theme": "light"}
session_settings = {"timeout": 60}

# 创建多个字典的组合视图
settings = ChainMap(session_settings, user_settings, defaults)

print(settings["theme"])
print(settings["language"])
print(settings["timeout"])

输出:

light
en
60

这创建了一个多字典的视图,依次查找各字典中的值,展示了如何按不同来源优先级检索设置项。

  1. os.path.commonpath() —— 轻松找出公共目录路径

是否曾需要找出多个文件路径的共同目录?os模块中的path.commonpath函数正好能做到这一点。

下面的代码能找出一组文件路径的最长公共目录,非常适合用于查找一组文件的基准目录:

import os.path

paths = [
    "/home/user/documents/work/report.pdf",
    "/home/user/documents/personal/taxes.xlsx",
    "/home/user/documents/work/presentation.pptx"
]

common = os.path.commonpath(paths)
print(f"Common directory: {common}")

输出:

Common directory: /home/user/documents

如上所示,这个函数在查找一组文件的公共根目录、构建相对路径等任务时非常实用。

结语

正如我们所见,Python标准库包含了许多专用函数,虽然不常用,但在特定场景下能提供非常优雅的解决方案。

下次你为某个常见问题编写复杂函数时,不妨先查查标准库,或许已经有了现成的解决办法!

你最喜欢的Python标准库里的冷门函数是什么?欢迎在评论区留言,我会在未来的文章中整理更多实用函数。祝你编程愉快!

最近发表
标签列表