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

Ruby实现文本文件指定词汇查找替换并另存为新文件

Ruby 实现方案

先定义需要替换的词汇列表,再修改代码实现逐行替换并写入新文件:

# 定义要替换的词汇列表
words_to_replace = ["foo", "bar", "敏感词"]

# 读取原文件同时写入新文件
File.open("text.txt", "r") do |input_file|
  File.open("text_modified.txt", "w") do |output_file|
    input_file.each do |line|
      # 复制原行避免修改原数据,遍历词汇列表完成替换
      modified_line = line.dup
      words_to_replace.each do |word|
        modified_line.gsub!(word, "DELETED")
      end
      # 将修改后的行写入新文件
      output_file.puts modified_line
    end
  end
end
  • gsub! 会替换当前行内所有匹配的目标词汇
  • 用 dup 复制原行,防止意外修改原文件的行内容
  • 同时打开读写文件,逐行处理降低内存占用
Python 实现方案

同样先定义词汇列表,利用文件上下文管理器完成逐行替换:

words_to_replace = ["foo", "bar", "敏感词"]

# 用with语句自动管理文件打开/关闭,指定编码避免乱码
with open("text.txt", "r", encoding="utf-8") as input_file, open("text_modified.txt", "w", encoding="utf-8") as output_file:
    for line in input_file:
        modified_line = line
        for word in words_to_replace:
            modified_line = modified_line.replace(word, "DELETED")
        output_file.write(modified_line)
  • replace() 方法会替换字符串内所有匹配的目标词汇
  • with 语句无需手动关闭文件,更安全简洁
  • 指定 encoding="utf-8" 适配中文等非ASCII字符场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 21:22:31