Python 中的 Unix 檔名模式匹配


在這裡,我們將瞭解如何使用 Python 獲取 UNIX shell 樣式的模式匹配技術。有一個名為 **fnmatch** 的模組用於執行此操作。此模組用於將檔名與模式進行比較,然後根據匹配情況返回 True 或 False。

要使用它,首先我們需要匯入 **fnmatch** 標準庫模組。

import fnmatch

在 Unix 終端中,有一些萬用字元用於匹配模式。它們如下所示:

  • ‘*’ 星號用於匹配所有內容。
  • ‘?’ 問號用於匹配單個字元。
  • [seq] 序列用於按順序匹配字元
  • [!seq] 非序列用於匹配序列中不存在的字元。

如果要搜尋星號或問號作為字元,則必須像這樣使用它們:[ * ] 或 [ ? ]

fnmatch() 方法

fnmatch() 方法接受兩個引數,分別是檔名和模式。此函式用於檢查檔名是否與給定模式匹配。當作業系統區分大小寫時,在匹配之前,引數將被規範化為大寫或小寫字母。

示例程式碼

import fnmatch
import os
file_pattern = 'test_f*'
files = os.listdir('./unix_files')
for filename in files:
   print('File: {}\t: {}'.format(filename, fnmatch.fnmatch(filename, file_pattern)))

輸出

$ python3 310.UNIX_filename.py
File: test_file5.txt : True
File: test_file2.png : True
File: test_file1.txt : True
File: another_file.txt : False
File: TEST_FILE4.txt : False
File: abc.txt : False
File: test_file3.txt : True
$

filter() 方法

filter() 方法也接受兩個引數。第一個是名稱,第二個是模式。此模式從所有檔名的列表中查詢匹配的檔名列表。

示例程式碼

import fnmatch
import os
file_pattern = 'test_f*'
files = os.listdir('./unix_files')
match_file = fnmatch.filter(files, file_pattern)
   print('All files:' + str(files))
      print('\nMatched files:' + str(match_file))

輸出

$ python3 310.UNIX_filename.py
All files:['test_file5.txt', 'test_file2.png', 'test_file1.txt', 'another_file.txt', 'TEST_FILE4.txt', 'abc.txt', 'test_file3.txt']
Matched files:['test_file5.txt', 'test_file2.png', 'test_file1.txt', 'test_file3.txt']
$

translate() 方法

translate() 方法接受一個引數。引數是一個模式。我們可以使用此函式將 shell 樣式模式轉換為另一種型別的模式,以便在 Python 中使用正則表示式進行匹配。

示例程式碼

import fnmatch, re
file_pattern = 'test_f*.txt'
unix_regex = fnmatch.translate(file_pattern)
regex_object = re.compile(unix_regex)
   print('Regular Expression:' + str(unix_regex))
      print('Match Object:' + str(regex_object.match('test_file_abcd123.txt')))

輸出

$ python3 310.UNIX_filename.py
Regular Expression:(?s:test_f.*\.txt)\Z
Match Object:<_sre.SRE_Match object; span=(0, 21), match='test_file_abcd123.txt'>
$

更新於: 2020-06-26

1K+ 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.