如何用Python实现类grep的多匹配行文件内容提取
Solution
Here's the modified code to support multiple pattern matches:
import re file_path = "mopsV22.txt" patterns = ['FRN 3', 'FRN 8'] # List of target patterns def grep_a(file_path, patterns, after_lines=2): with open(file_path, 'r') as file: lines = file.readlines() match_lines = [] for i, line in enumerate(lines): # Check if any pattern matches the current line if any(re.search(pattern, line) for pattern in patterns): match_lines.extend(lines[i:i+1+after_lines]) return match_lines matched_lines = grep_a(file_path, patterns, after_lines=0) for line in matched_lines: print(line, end='')
Key Changes:
- Changed the single
patternparameter topatterns(accepts a list of target strings) - Used
any(re.search(pattern, line) for pattern in patterns)to check if the line matches any of the input patterns - Updated the function call to pass a list of desired patterns (
['FRN 3', 'FRN 8']) - Added the missing
import restatement (required for regex operations)
Alternative: Combine Patterns into a Single Regex
For better performance (especially with many patterns), combine them into a single regex using alternation (|). Adding ^ ensures matches only at the start of the line (more precise for your use case):
import re file_path = "mopsV22.txt" # Combine patterns to match lines starting with FRN 3 or FRN 8 pattern = r'^FRN 3|^FRN 8' def grep_a(file_path, pattern, after_lines=2): with open(file_path, 'r') as file: lines = file.readlines() match_lines = [] for i, line in enumerate(lines): if re.search(pattern, line): match_lines.extend(lines[i:i+1+after_lines]) return match_lines matched_lines = grep_a(file_path, pattern, after_lines=0) for line in matched_lines: print(line, end='')
内容的提问来源于stack exchange,提问作者Ketan
相关产品推荐
相关产品推荐

