【问题标题】:Remove part of string (downcase) and keep the original (upcase) in Ruby删除部分字符串(小写)并在 Ruby 中保留原始字符串(大写)
【发布时间】:2019-02-05 08:59:06
【问题描述】:

我想从 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

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

【问题讨论】:

  • 试试def remove_appellations_in_string(string, region_id) stopwords.each do |stop| rx = stop.name.chars.map { |c| "[#{c}#{I18n.transliterate(c)}]" }.join string.gsub!(Regexp.new(rx, 'i'), ' ') end return ' ' + string + ' ' end。这是一个代码 sn-p - ideone.com/IevjIW
  • 不确定您所说的“汽车索引”是什么意思。
  • 什么是I18n?如果您正在使用某些库,请参考。
  • 什么是stopwords
  • Wiktor 的答案就像一个魅力!但是rx = I18n.transliterate(stop.name) 也可以使用正则表达式string.gsub!(Regexp.new(rx, 'i'), ' ')。那么rx = stop.name.chars.map { |c| "[#{c}#{I18n.transliterate(c)}]" }.join 的优势是什么?

标签: ruby string gsub


【解决方案1】:

这似乎有效:

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"

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

这就是你所追求的吗?如果您有任何问题,请告诉我。

【讨论】:

  • 请注意,音译字符串不一定以相同长度的字符串结尾。
  • 你好,是的,是这样的!谢谢 SRack。我做了一些更改以澄清事情。 index_stopword_start = unaccent_string.index(unaccent_stopword) next if index_stopword_start.nil? index_stopword_end = index_stopword_start + unaccent_stopword.length # new string string = string[0..(index_stopword_start - 1)] + string[index_stopword_end..-1]
  • Sawa,是的,我知道音译可能是某些语言的问题。谢谢。
  • 这是@alex.bour 的答案吗?如果可以,适合接受吗?
猜你喜欢
  • 2016-01-13
  • 2019-07-13
  • 1970-01-01
  • 2019-11-22
  • 2011-05-01
  • 1970-01-01
  • 2022-11-22
  • 2016-11-26
  • 1970-01-01
相关资源
最近更新 更多