Python 開發者必知的 13 種文本匹配模式
文本匹配是編程中非常常見的任務,特別是在處理大量數據時。Python 提供了多種強大的工具來幫助我們實現高效的文本匹配。本文將詳細介紹 13 種常用的文本匹配模式,從簡單的字符串方法到復雜的正則表達式,逐步引導你掌握這些強大的工具。
1. 使用 in 關鍵字
最簡單的文本匹配方式就是使用 in 關鍵字,檢查一個字符串是否包含另一個字符串。
text = "Hello, world!"
substring = "world"
if substring in text:
print(f"'{substring}' is found in '{text}'")
else:
print(f"'{substring}' is not found in '{text}'")
輸出:
'world' is found in 'Hello, world!'
2. 使用 str.find()
str.find() 方法返回子字符串在字符串中的位置,如果找不到則返回 -1。
text = "Hello, world!"
substring = "world"
index = text.find(substring)
if index != -1:
print(f"'{substring}' is found at index {index} in '{text}'")
else:
print(f"'{substring}' is not found in '{text}'")
輸出:
'world' is found at index 7 in 'Hello, world!'
3. 使用 str.index()
str.index() 方法類似于 str.find(),但如果沒有找到子字符串,它會拋出一個 ValueError。
text = "Hello, world!"
substring = "world"
try:
index = text.index(substring)
print(f"'{substring}' is found at index {index} in '{text}'")
except ValueError:
print(f"'{substring}' is not found in '{text}'")
輸出:
'world' is found at index 7 in 'Hello, world!'
4. 使用 str.startswith()
str.startswith() 方法檢查字符串是否以指定的前綴開頭。
text = "Hello, world!"
if text.startswith("Hello"):
print(f"'{text}' starts with 'Hello'")
else:
print(f"'{text}' does not start with 'Hello'")
輸出:
'Hello, world!' starts with 'Hello'
5. 使用 str.endswith()
str.endswith() 方法檢查字符串是否以指定的后綴結尾。
text = "Hello, world!"
if text.endswith("world!"):
print(f"'{text}' ends with 'world!'")
else:
print(f"'{text}' does not end with 'world!'")
輸出:
'Hello, world!' ends with 'world!'
6. 使用 str.count()
str.count() 方法返回子字符串在字符串中出現的次數。
text = "Hello, world! Hello, Python!"
count = text.count("Hello")
print(f"'Hello' appears {count} times in '{text}'")
輸出:
'Hello' appears 2 times in 'Hello, world! Hello, Python!'
7. 使用 str.replace()
str.replace() 方法用于替換字符串中的子字符串。
text = "Hello, world!"
new_text = text.replace("world", "Python")
print(f"Original: {text}")
print(f"Replaced: {new_text}")
輸出:
Original: Hello, world!
Replaced: Hello, Python!
8. 使用 re 模塊的基本匹配
re 模塊提供了正則表達式的支持,可以進行更復雜的文本匹配。
import re
text = "Hello, world!"
pattern = r"world"
match = re.search(pattern, text)
if match:
print(f"Pattern '{pattern}' is found in '{text}'")
else:
print(f"Pattern '{pattern}' is not found in '{text}'")
輸出:
Pattern 'world' is found in 'Hello, world!'
9. 使用 re.findall()
re.findall() 方法返回所有匹配的子字符串。
import re
text = "Hello, world! Hello, Python!"
pattern = r"Hello"
matches = re.findall(pattern, text)
print(f"Pattern '{pattern}' is found {len(matches)} times in '{text}'")
輸出:
Pattern 'Hello' is found 2 times in 'Hello, world! Hello, Python!'
10. 使用 re.sub()
re.sub() 方法用于替換正則表達式匹配的子字符串。
import re
text = "Hello, world!"
pattern = r"world"
replacement = "Python"
new_text = re.sub(pattern, replacement, text)
print(f"Original: {text}")
print(f"Replaced: {new_text}")
輸出:
Original: Hello, world!
Replaced: Hello, Python!
11. 使用 re.split()
re.split() 方法根據正則表達式分割字符串。
import re
text = "Hello, world! Hello, Python!"
pattern = r"!"
parts = re.split(pattern, text)
print(f"Text split by '!': {parts}")
輸出:
Text split by '!': ['Hello, world', ' Hello, Python', '']
12. 使用 re.compile()
re.compile() 方法編譯正則表達式,提高多次使用的效率。
import re
text = "Hello, world! Hello, Python!"
pattern = re.compile(r"Hello")
matches = pattern.findall(text)
print(f"Pattern 'Hello' is found {len(matches)} times in '{text}'")
輸出:
Pattern 'Hello' is found 2 times in 'Hello, world! Hello, Python!'
13. 使用 re.escape()
re.escape() 方法轉義特殊字符,防止它們被解釋為正則表達式的一部分。
import re
text = "Hello, world! Hello, Python!"
special_char = "."
escaped_char = re.escape(special_char)
pattern = f"{escaped_char}"
matches = re.findall(pattern, text)
print(f"Pattern '{escaped_char}' is found {len(matches)} times in '{text}'")
輸出:
Pattern '\.' is found 2 times in 'Hello, world! Hello, Python!'
實戰案例:日志文件分析
假設你有一個日志文件,記錄了用戶的訪問信息,格式如下:
2023-10-01 12:00:00 - User1 - Page1
2023-10-01 12:01:00 - User2 - Page2
2023-10-01 12:02:00 - User1 - Page3
2023-10-01 12:03:00 - User3 - Page1
我們需要分析這個日志文件,統計每個用戶訪問的頁面次數。
import re
from collections import defaultdict
# 假設這是日志文件的內容
log_content = """
2023-10-01 12:00:00 - User1 - Page1
2023-10-01 12:01:00 - User2 - Page2
2023-10-01 12:02:00 - User1 - Page3
2023-10-01 12:03:00 - User3 - Page1
"""
# 編譯正則表達式
pattern = re.compile(r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) - (\w+) - (\w+)")
# 創建一個字典來存儲用戶訪問的頁面次數
user_page_count = defaultdict(lambda: defaultdict(int))
# 遍歷日志內容,匹配每一行
for line in log_content.strip().split('\n'):
match = pattern.match(line)
if match:
timestamp, user, page = match.groups()
user_page_count[user][page] += 1
# 輸出結果
for user, pages in user_page_count.items():
print(f"User: {user}")
for page, count in pages.items():
print(f" Page: {page}, Count: {count}")
輸出:
User: User1
Page: Page1, Count: 1
Page: Page3, Count: 1
User: User2
Page: Page2, Count: 1
User: User3
Page: Page1, Count: 1
總結
本文介紹了 13 種常用的文本匹配模式,包括簡單的字符串方法和復雜的正則表達式。通過這些方法,你可以高效地處理各種文本匹配任務。每種方法都有其適用場景,選擇合適的方法可以大大提高你的編程效率。最后,我們通過一個實戰案例展示了如何使用這些方法來分析日志文件,統計用戶訪問的頁面次數。