繁体   English   中英

查找和替换红宝石,除了一些短语文本文件

[英]Find and replace ruby except some phrases text file

我敢肯定我做错了。 但是我希望该程序通过“ phone_numbers.txt”运行,并替换所有重复的内容,除了["Employee Marked Urgency as: low", "Employee Marked Urgency as: high"]此代码的结果绝对没有。 没有改变。 有小费吗?

file_names = ['phone_numbers.txt']
    file_names.each do |file_name|
      words_to_exclude = ["Employee Marked Urgency as: low", "Employee Marked Urgency as: high"]
      text = File.read(file_name)
      lines = text.split("\n")
      new_contents = lines.uniq.reject do |word|
        words_to_exclude.include? word
      end.join("\n")
      File.open(file_name, "w") { |file| file.puts new_contents }
    end

我不确定我是否理解正确,但是将Array#uniq与一个块配合使用应该可以解决问题:

require 'digest/sha1' # to generate uniqs

file_names = ['phone_numbers.txt']
words_to_exclude = ["Employee Marked Urgency as: low",
                    "Employee Marked Urgency as: high"]

file_names.each do |file_name|
  res = File.readlines(file_name).each_with_index.uniq do |s, idx|
    words_to_exclude.include?(s) ?
      Digest::SHA1.hexdigest(idx.to_s) : s
  end.join("\n")
  File.write(file_name, res)
end

这是怎么回事:如果我们遇到列表中的单词,则会生成一个足够唯一的字符串,无论如何都要通过; 否则,我们将使用原始字符串进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM