You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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 pattern parameter to patterns (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 re statement (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 21:25:59