【问题标题】:Replace specified phrase with * within text在文本中用 * 替换指定的短语
【发布时间】:2018-09-30 12:26:52
【问题描述】:

我的目的是接受一段文本并找到我要 REDACT 或替换的指定短语。

我创建了一个方法,它接受一个参数作为文本字符串。我将该字符串分解为单个字符。比较这些字符,如果匹配,我将这些字符替换为*

def search_redact(text)
  str = ""

  print "What is the word you would like to redact?"
  redacted_name = gets.chomp
  puts "Desired word to be REDACTED #{redacted_name}! "
  #splits name to be redacted, and the text argument into char arrays
  redact = redacted_name.split("")
  words = text.split("")

  #takes char arrays, two loops, compares each character, if they match it 
  #subs that character out for an asterisks
  redact.each do |x|
    if words.each do |y|
      x == y
      y.gsub!(x, '*') # sub redact char with astericks if matches words text
       end # end loop for words y
    end # end if statment
 end # end loop for redact x

# this adds char array to a string so more readable  
words.each do |z|
  str += z
end
# prints it out so we can see, and returns it to method
  print str
  return str
end

# calling method with test case
search_redact("thisisapassword")

#current issues stands, needs to erase only if those STRING of characters are 
# together and not just anywehre in the document 

如果我输入一个与文本的其他部分共享字符的短语,例如,如果我调用:

search_redact("thisisapassword")

那么它也会替换该文本。当它接受用户的输入时,我只想摆脱文本密码。但它看起来像这样:

thi*i**********

请帮忙。

【问题讨论】:

    标签: ruby gsub redaction


    【解决方案1】:

    这是一个经典的窗口问题,用于在字符串中查找子字符串。有很多方法可以解决这个问题,有些方法比其他方法更有效,但我会给你一个简单的方法来看看,它尽可能多地使用你的原始代码:

    def search_redact(text)
      str = ""
    
      print "What is the word you would like to redact?"
      redacted_name = gets.chomp
      puts "Desired word to be REDACTED #{redacted_name}! "
      redacted_name = "password"
      #splits name to be redacted, and the text argument into char arrays
      redact = redacted_name.split("")
      words = text.split("")
    
      words.each.with_index do |letter, i|
        # use windowing to look for exact matches
        if words[i..redact.length + i] == redact
          words[i..redact.length + i].each.with_index do |_, j|
            # change the letter to an astrisk
            words[i + j] = "*"
          end
        end
      end
    
      words.join
    end
    
    # calling method with test case
    search_redact("thisisapassword")
    

    这里的想法是我们正在利用数组==,它允许我们说["a", "b", "c"] == ["a", "b", "c"]。所以现在我们只是遍历输入并询问这个子数组是否等于另一个子数组。如果它们匹配,我们知道我们需要更改值,因此我们循环遍历每个元素并将其替换为 *

    【讨论】:

    • 非常清晰和有用。这是完美的答案。你是一位伟大的老师。非常感谢你启发我。我现在将研究更多关于窗口的信息,我是新手。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2014-02-04
    • 2023-03-18
    相关资源
    最近更新 更多