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

求可搜索指定文件并提取目标内容的Python脚本(整合现有代码)

解决方案

完整整合脚本

以下是整合了目录搜索与内容提取的Python脚本,可自动查找指定目录下的My_data.txt,并提取匹配「Name,Age」模式的内容:

import os
import re

def find_and_extract(target_file, root_dir, pattern):
    # 遍历根目录下所有子目录与文件
    for dirpath, _, filenames in os.walk(root_dir):
        if target_file in filenames:
            file_path = os.path.join(dirpath, target_file)
            print(f"找到目标文件: {file_path}")
            # 读取文件并逐行匹配模式
            with open(file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    match_result = re.search(pattern, line)
                    if match_result:
                        print(f"匹配内容: {line.strip()}")

# 配置参数
TARGET_FILE = "My_data.txt"
SEARCH_ROOT = "/root/convey"  # 替换为你的目标搜索目录
MATCH_PATTERN = r'Name,Age'  # 可按需调整,比如提取姓名年龄值用 r'(\w+),(\d+)'

# 执行脚本
find_and_extract(TARGET_FILE, SEARCH_ROOT, MATCH_PATTERN)

关键说明

  • 目录搜索:通过os.walk遍历指定根目录的所有层级,自动定位My_data.txt
  • 内容匹配:使用正则表达式re.search实现精准匹配,比原代码的in判断更灵活:
    • 若仅需查找包含Name,Age的行,保留r'Name,Age'即可
    • 若要提取类似张三,25的姓名-年龄组合,可将模式改为r'^[^,]+,\d+$'
    • 若需单独获取姓名和年龄值,用分组正则r'(\w+),(\d+)',通过match_result.group(1)/group(2)提取
  • 编码处理:添加encoding='utf-8'避免文件读取时的乱码问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:25:33