# -*- coding: utf-8 -*-
"""从已抓文本中按正则抽取相关片段（去空行，截取上下文窗口）。"""
import sys, io, re, glob
pat = sys.argv[1]
files = sys.argv[2:]
for f in files:
    try:
        t = io.open(f, encoding='utf-8', errors='ignore').read()
    except Exception as e:
        print('ERR', f, e); continue
    t = re.sub(r'[ \t]+', ' ', t)
    lines = [l.strip() for l in t.split('\n') if l.strip()]
    print('=====', f.split('\\')[-1], len(lines), 'lines')
    hits = 0
    for i, l in enumerate(lines):
        if re.search(pat, l, re.I):
            print('|', l[:300])
            hits += 1
            if hits > 60:
                print('... truncated'); break
