首页 > 解决方案 > 删除部分字符串(小写)并在 Ruby 中保留原始字符串(大写)

问题描述

我想从 ruby​​ 字符串中删除一组单词,使用单词的小写和非重音版本,并使用当前大小写和当前重音保留原始字符串。

例如:

string = "Château Dupont Vallée du Rhône" 
stopwords= "vallee du Rhone"

期望的输出:string = "Château Dupont"

到目前为止,我能做的是使用小写的非重音字符串来删除单词:

string = "chateau dupont vallee du rhone" 
stopword = "vallee du rhone"

示例输出:string = "chateau dupont"

实际上,我想获取原始字符串,但使用单词的小写无重音版本删除字符串。

我的代码:

def remove_appellations_in_string(string, region_id)
   down_trans_string = I18n.transliterate(string.dup)      
   # custom request to order by max length in name            
   stopwords.each do |stop|
      # downcase/unaccent stopword
      down_trans_stop = I18n.transliterate(stop.name.downcase)
      # remove
      down_trans_string.gsub!(down_trans_stop, ' ')
    end    
    return ' ' + string + ' ' 
  end

我想我需要使用正则表达式或获取一种方法来获取停用词的索引以将它们从原始字符串中删除。

标签: rubystringgsub

解决方案


这似乎有效:

string = "Château Dupont Vallée du Rhône"   
stopword = "vallee du rhone"  
index = I18n.transliterate(string).downcase.index(I18n.transliterate(stopword).downcase)
string[0..(index - 1)] + string[(index + stopword.length)..-1]

# => "Château Dupont "

stopword = "Dupont" 
index = I18n.transliterate(string).downcase.index(I18n.transliterate(stopword).downcase)
string[0..(index - 1)] + string[(index + stopword.length)..-1]

# => "Château  Vallée du Rhône"

它按照您的建议进行 - 获取停用词与剥离字符串匹配的位置的索引,并在此之前和之后返回文本。

这就是你所追求的吗?让我知道你是如何处理它的,或者如果你有任何问题。


推荐阅读