掌握 fnmatchfnmatchcase:从文件名到街道地址的全能字符串匹配技巧

在处理文件路径或字符串匹配时,Python 提供了两个非常实用的函数:fnmatchfnmatchcase。这两个函数都位于 fnmatch 模块中,用于实现类似 Unix shell 的通配符匹配。本文将详细介绍这两个函数的功能、区别以及如何使用它们,并通过示例来加深理解。

导入模块

首先,在使用 fnmatchfnmatchcase 之前,需要从 Python 标准库中导入 fnmatch 模块:

import fnmatch
fnmatch 函数
  • 功能fnmatch 函数用于测试给定的字符串是否符合指定的模式(pattern)。它对大小写不敏感,即如果操作系统认为文件名是大小写不敏感的,则该函数也会执行相应的大小写折叠。
  • 参数
  • filename (str):待匹配的字符串。
  • pattern (str):模式字符串,支持的通配符包括 *(零个或多个字符)、?(单个字符)等。
  • 返回值:如果 filename 符合 pattern,则返回 True;否则返回 False

示例

print(fnmatch.fnmatch('example.txt', '*.txt'))  # True
print(fnmatch.fnmatch('Example.TXT', '*.txt'))  # True (忽略大小写)
print(fnmatch.fnmatch('test.py', '*.py'))       # True
print(fnmatch.fnmatch('test.c', '*.cpp'))      # False
fnmatchcase 函数
  • 功能:与 fnmatch 类似,但 fnmatchcase 是区分大小写的。这意味着即使在大小写不敏感的操作系统上,它仍然会严格按照模式中的大小写进行匹配。
  • 参数返回值fnmatch 完全相同。

示例

print(fnmatch.fnmatchcase('example.txt', '*.txt'))  # True
print(fnmatch.fnmatchcase('Example.TXT', '*.txt'))  # False (区分大小写)
print(fnmatch.fnmatchcase('Test.PY', '*.PY'))      # True
print(fnmatch.fnmatchcase('test.cpp', '*.CPP'))    # False
应用场景
  • 文件过滤:当你需要根据某种模式筛选出特定类型的文件时,这些函数特别有用。例如,在目录中查找所有 .jpg 文件。
  • URL 匹配:虽然主要设计用于文件名匹配,但也可以灵活地应用于其他形式的字符串匹配,比如 URL 路径等。
  • 非文件名式的字符串匹配:除了文件名,这些函数还可以用于其他类型的字符串匹配,如街道地址等。
非文件名式的字符串匹配示例

假设你有一组街道地址,并希望根据某些模式进行筛选。例如,你想找到所有包含 “Main Street” 的地址,或者只包含数字作为街道号的地址。

示例代码

# 一组街道地址
addresses = [
    '123 Main Street',
    '456 Elm Avenue',
    '789 Oak Road',
    '101 Maple Lane',
    '111 Pine Street',
    '222 Main St',
    '333 Central Blvd'
]

# 筛选出包含 "Main Street" 的地址
main_street_addresses = [addr for addr in addresses if fnmatch.fnmatch(addr, '*Main Street*')]
print("Addresses containing 'Main Street':", main_street_addresses)

# 筛选出只有数字作为街道号的地址
numeric_street_addresses = [addr for addr in addresses if fnmatch.fnmatch(addr, '[0-9]* *')]
print("Addresses with numeric street numbers:", numeric_street_addresses)

输出

Addresses containing 'Main Street': ['123 Main Street', '222 Main St']
Addresses with numeric street numbers: ['123 Main Street', '456 Elm Avenue', '789 Oak Road', '101 Maple Lane', '111 Pine Street', '222 Main St', '333 Central Blvd']

在这个示例中,我们使用 fnmatch 来筛选出包含 “Main Street” 的地址,以及只有数字作为街道号的地址。这展示了 fnmatch 不仅可以用于文件名匹配,还可以灵活地应用于其他类型的字符串匹配任务。

总结

fnmatchfnmatchcase 是强大的工具,可以帮助开发者轻松实现基于通配符的字符串匹配。选择哪个函数取决于你的具体需求——如果你希望匹配过程不受大小写影响,则应选用 fnmatch;若需严格遵守大小写规则,则 fnmatchcase 更合适。了解并掌握这两个函数可以让你在处理涉及模式匹配的任务时更加得心应手。

欢迎点赞、关注、转发、收藏!!!