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

基于Python实现:捕获替换词并更新TXT文件指定字符串

完善Python文本替换代码

修正后的完整代码

import re

# 输入文本示例
input_text = "No es Marín sino que es Marina"

# 正则捕获待替换词和目标替换词(可根据实际输入格式调整正则规则)
pattern = r"No es (\w+) sino que es (\w+)"
match = re.search(pattern, input_text)

if match:
    word_to_replace = match.group(1)
    replacement_word = match.group(2)
    
    # 处理文件替换逻辑
    file_path = "names.txt"
    try:
        # 读取文件所有行
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        # 查找待替换词所在行并替换,兼容行尾带/不带换行符的情况
        target_line_with_newline = word_to_replace + '\n'
        if target_line_with_newline in lines:
            index = lines.index(target_line_with_newline)
            lines[index] = replacement_word + '\n'
        elif word_to_replace in lines:
            index = lines.index(word_to_replace)
            lines[index] = replacement_word
        
        # 将修改后的内容写入文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.writelines(lines)
        
        print(f"已成功将文件中的'{word_to_replace}'替换为'{replacement_word}'")
    except FileNotFoundError:
        print(f"错误:未找到文件 {file_path}")
    except ValueError:
        print(f"错误:文件中未找到待替换的词 '{word_to_replace}'")
else:
    print("未匹配到待替换词和目标替换词")

关键修正与说明

  • 修复索引错误:替换了原代码中错误的索引查找逻辑,同时兼容文件行尾带换行符和不带的两种场景,避免匹配失败。
  • 完善文件读写逻辑:用with语句实现安全的文件读写,先读取所有行完成修改后再写入,保证文件操作的稳定性。
  • 添加异常处理:捕获文件不存在、待替换词未找到的异常,提升代码健壮性。
  • 正则适配:示例正则针对给定的输入文本格式编写,若输入文本格式有变化,需对应调整pattern规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:20:46