【发布时间】: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的优势是什么?