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

如何用Python遍历两个文件并提取匹配行的前一行

问题描述

这是names.txt文件内容:

David
Mary
Rose
Saeed

这是emails.txt文件内容:

- address1@gmail.com
  - Mary
  - address2@gmail.com
  - Rose
  - address3@hotmail.com
  - David
  - address4@yahoo.com
  - Saeed
  - address5@gmail.com
  - Jones

emails.txt中的邮箱数量多于names.txt中的名字数量。

需求:针对names.txt中的每个名字,在emails.txt中匹配该名字,并提取匹配行的前一行内容。比如匹配David时,对应的邮箱是address3@hotmail.com。

现有Python代码仅能打印names.txt的第一行内容:

import re

with open('names.txt', 'r') as file:
    with open('emails.txt', 'r') as emails:
        for name in file:
            for email in emails:
                if re.search(name, email):
                    print(email)

问题分析

现有代码的核心问题是:emails文件对象是迭代器,第一次遍历后就指向了文件末尾,后续循环处理其他名字时不会重新读取文件内容,因此只能处理第一个名字。

解决方案

方案一:预存邮件行,遍历匹配

先把emails.txt的所有行读取到列表中,这样每次匹配名字时都能从头遍历查找:

# 读取所有名字,去除换行符和空白行
with open('names.txt', 'r') as f:
    names = [name.strip() for name in f if name.strip()]

# 读取所有邮件行,去除换行符
with open('emails.txt', 'r') as f:
    email_lines = [line.strip() for line in f]

# 遍历每个名字,查找对应邮箱
for name in names:
    for idx, line in enumerate(email_lines):
        # 去掉行首的"- "后匹配名字
        if line.lstrip('- ').strip() == name:
            if idx > 0:
                # 提取前一行的邮箱,清理格式
                email = email_lines[idx-1].lstrip('- ').strip()
                print(f"{name}: {email}")
            break

方案二:遍历邮件行时记录前一行

遍历邮件内容时实时记录上一行内容,遇到匹配的名字就直接输出前一行的邮箱:

# 读取所有名字存入集合,方便快速判断
with open('names.txt', 'r') as f:
    names_set = {name.strip() for name in f if name.strip()}

prev_line = None
with open('emails.txt', 'r') as f:
    for line in f:
        current_line = line.strip()
        # 清理当前行格式后检查是否是目标名字
        current_name = current_line.lstrip('- ').strip()
        if current_name in names_set:
            if prev_line:
                email = prev_line.lstrip('- ').strip()
                print(f"{current_name}: {email}")
        # 更新前一行记录
        prev_line = current_line

输出结果

两种方案都会输出:

David: address3@hotmail.com
Mary: address1@gmail.com
Rose: address2@gmail.com
Saeed: address4@yahoo.com

内容的提问来源于stack exchange,提问作者Saeed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 05:12:24