【问题标题】:replace words in a string and re join them替换字符串中的单词并重新加入它们
【发布时间】:2018-01-31 11:38:13
【问题描述】:

嗨,我正在构建一个函数,让我在字符串中获取“u”或“you”的任何实例,并将其替换为特定的单词。我可以进去隔离实例没问题,但我无法正确输出单词。到目前为止,我有。

def autocorrect(input)

 #replace = [['you','u'], ['your sister']]
 #replace.each{|replaced| input.gsub!(replaced[0], replaced[1])}
 input.split(" ")

 if (input == "u" && input.length == 1) || input == "you"
   input.replace("your sister")
 end

 input.join(" ")
end

理想的输出是:

autocorrect("I am so smitten with you")

"I am smitten with your sister"

我不知道如何让最后一部分正确,我想不出一个好的方法来使用。任何帮助将不胜感激。

【问题讨论】:

  • input == "u" 暗示input.length 为1。后面的检查是多余的。

标签: ruby string replace split


【解决方案1】:

简单的数组映射就可以完成这项工作:

"I am u so smuitten with utopia you".split(' ').map{|word| %w(you u).include?(word) ? 'your sister' : word}.join(' ')
#=> "I am your sister so smuitten with utopia your sister"

你的方法是:

def autocorrect(input)
  input.split(' ').map{|word| %w(you u).include?(word) ? 'your sister' : word}.join(' ')
end

autocorrect("I am so smitten with you")
#=> "I am smitten with your sister"

【讨论】:

    【解决方案2】:

    您的代码遇到的问题是您调用了input.split(" "),但您没有将其保存到任何内容,然后您检查input == "u" # ...,而input 仍然是整个字符串,所以如果你调用了autocorrect('u')autocorrect('you') 你会得到"your sister"except 用于下一行:input.join(" ") 会抛出一个错误。

    这个错误是因为,记住input仍然是原始字符串,而不是每个单词的数组,并且字符串没有join方法。

    为了让您的代码以尽可能少的更改工作,您可以将其更改为:

    def autocorrect(input)
      #replace = [['you','u'], ['your sister']]
      #replace.each{|replaced| input.gsub!(replaced[0], replaced[1])}
      input.split(" ").map do |word|
        if (word == "u" && word.length == 1) || word == "you"
          "your sister"
        else
          word
        end
      end.join(" ")
    end
    

    所以,现在,您正在split(" ") 输入之后对每个单词进行处理,并且您正在对照"u""you" 检查每个单词,而不是整个输入字符串.然后,您映射替换词或原始词,然后将它们连接回单个字符串以返回它们。


    作为另一种更短的方法,您可以使用String#gsub,它可以将Hash 作为第二个参数来进行替换:

    如果第二个参数是一个哈希,匹配的文本是它的一个键,对应的值就是替换字符串。

    def autocorrect(input)
      replace = { 'you' => 'your sister',
                  'u' => 'your sister',
                  'another word' => 'something else entirely' }
    
      input.gsub(/\b(#{replace.keys.join('|')})\b/, replace)
    end
    
    autocorrect("I am u so smitten with utopia you and another word")
    # => "I am your sister so smitten with utopia your sister and something else entirely"
    

    该示例中的正则表达式看起来像:

    /\b(you|u|another word)\b/
    

    \b 是任何单词边界。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      相关资源
      最近更新 更多