查找字串简洁版

以下是简洁版的 Python 代码,用于查找多个字符串,要求它们出现在相近的位置(间隔不超过 `max_distance` 个字符),并输出包含这些字符串前后 40 个字的内容:

### 简洁版代码
```python
import re

def search_and_extract(input_file, output_file, search_texts, max_distance=40):
    with open(input_file, 'r', encoding='utf-8') as file:
        content = file.read()

    # 构建正则表达式模式
    pattern = re.compile(
        r'.{0,40}%s.{0,%d}%s.{0,40}' % (
            re.escape(search_texts[0]), max_distance, re.escape(search_texts[1])
        )
    )

    # 查找匹配的内容
    matches = pattern.findall(content)

    # 写入结果
    with open(output_file, 'w', encoding='utf-8') as file:
        for match in matches:
            file.write(match + '\n')

# 示例用法
input_file = 'input.txt'  # 输入文件路径
output_file = 'output.txt'  # 输出文件路径
search_texts = ['字符串1', '字符串2']  # 要查找的多个字符串
max_distance = 40  # 字符串之间的最大间隔字符数

search_and_extract(input_file, output_file, search_texts, max_distance)
```

---

### 代码说明:
1. **正则表达式**:
   - `r'.{0,40}%s.{0,%d}%s.{0,40}'`:
     - `.{0,40}`:匹配任意字符(最多 40 个)。
     - `%s`:插入第一个字符串(`search_texts[0]`)。
     - `.{0,%d}`:匹配两个字符串之间的字符(最多 `max_distance` 个)。
     - `%s`:插入第二个字符串(`search_texts[1]`)。
     - `.{0,40}`:匹配第二个字符串后的任意字符(最多 40 个)。

2. **`re.escape`**:
   - 对字符串进行转义,确保正则表达式中的特殊字符(如 `.`、`*` 等)被正确处理。

3. **`pattern.findall`**:
   - 查找所有匹配的内容。

4. **写入结果**:
   - 将匹配的内容逐行写入输出文件。

---

### 示例:
#### 输入文件 (`input.txt`):
```plaintext
这是一个测试文档,包含一些字符串1和其他内容。
字符串1和字符串2之间的间隔不超过40个字符。
这是一个简单的测试,用于演示多字符串查找功能。
```

#### 查找字符串:
```python
search_texts = ['字符串1', '字符串2']
max_distance = 40
```

#### 输出文件 (`output.txt`):
```plaintext
这是一个测试文档,包含一些字符串1和其他内容。
字符串1和字符串2之间的间隔不超过40个字符。
```

posted @ 2025-02-06 05:04  黄光  阅读(20)  评论(0)    收藏  举报