将字符串中的单词替换为定义为哈希值的单词

时间:2019-02-27 20:56:38

标签: ruby

目的是用字典中定义的值替换字符串中的特定单词。

dictionary =
    {"Hello" => "hi",
    "to, two, too" => "2",
    "for, four" => "4",
    "be" => "b",
    "you" => "u",
    "at" => "@",
    "and" => "&"
}

def word_substituter(tweet)
    tweet_array = tweet.split(',') ##converting the string to array
    tweet_array.each do |word|
        if word === dictionary.keys ##if the words of array are equal to the keys of the dictionary
         word == dictionary.values ##then now the words are now the the values of the dictionary
         puts word
        end
      end 
    word.join(", ")
end

word_substituter("Hey guys, can anyone teach me how to be cool? I really want to be the best at everything, you know what I mean? Tweeting is super fun you guys!!!!")

我将感谢您的帮助。你能解释一下吗?

2 个答案:

答案 0 :(得分:0)

天真枚举

DICTIONARY = {
  "Hello" => "hi",
  "to, two, too" => "2",
  "for, four" => "4",
  "be" => "b",
  "you" => "u",
  "at" => "@",
  "and" => "&"
}.freeze

def word_substituter(tweet)
  dict = {}
  DICTIONARY.keys.map { |k| k.split(', ') }.flatten.each do |w|
    DICTIONARY.each { |k, v| dict.merge!(w => v) if k.include?(w) }
  end

  tweet.split(' ').map do |s|
    dict.each { |k, v| s.sub!(/#{k}/, v) if s =~ /\A#{k}[[:punct:]]*\z/ }
    s
  end.join(' ')
end

word_substituter("Hey guys, I'm Robe too. Can anyone teach me how to be cool? I really want to be the best at everything, you know what I mean? Tweeting is super fun you guys!!!!")

# => "Hey guys, I'm Robe 2. Can anyone teach me how 2 b cool? I really want 2 b the best @ everything, u know what I mean? Tweeting is super fun u guys!!!!"

答案 1 :(得分:0)

我觉得这提供了一个相当简单的解决方案:

SELECT * FROM MYTABLE WHERE CONTAINS(Name, 'file')

将其分解为步骤:

  • 该方法发送一条推文并创建一个副本
  • 它将其传递给tap,以便从方法调用中返回
  • 它遍历DICTIONARY = { "Hello" => "hi", "to, two, too" => "2", "for, four" => "4", "be" => "b", "you" => "u", "at" => "@", "and" => "&" }.freeze def word_substituter(tweet) tweet.dup.tap do |t| DICTIONARY.each { |key, replacement| t.gsub!(/\b(#{key.split(', ').join('|')})\b/, replacement) } end end word_substituter("Hey guys, can anyone teach me how to be cool? I really want to be the best at everything, you know what I mean? Tweeting is super fun you guys!!!!") # => "Hey guys, can anyone teach me how 2 b cool? I really want 2 b the best @ everything, u know what I mean? Tweeting is super fun u guys!!!!"
  • DICTIONARY转换为正则表达式匹配器(例如key
  • 将此内容传递给gsub!,并将所有匹配项替换为/\b(to|two|too)\b/

如果您要替换单词中出现的单词(例如replacement),则可以删除正则表达式中对单词边界(what => wh@)的检查。

一个陷阱是,如果您词典中的任何键包含正则表达式匹配器,则都需要进行一些修改:如果您使用\b,则该点将匹配任何字符并将其包含在替换的字符中。 Regexp.escape是您的朋友。

希望这会有所帮助-让我知道您的生活。