ruby - 删除部分字符串(小写)并在 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
我想我需要使用正则表达式或获取一种方法来获取停用词的索引以将它们从原始字符串中删除。
解决方案
这似乎有效:
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"
它按照您的建议进行 - 获取停用词与剥离字符串匹配的位置的索引,并在此之前和之后返回文本。
这就是你所追求的吗?让我知道你是如何处理它的,或者如果你有任何问题。
推荐阅读
- javascript - 如何从Javascript中的集合数组中提取键的值
- java - 选择插入查询循环
- javascript - JS或Jquery中黄金价格的解析结果
- ffmpeg - 如何在背景图像上叠加视频?
- ansible - 迭代 Ansible 调试输出
- excel - 第一次迭代后循环文件夹中的所有文件失败
- docker - 使用 docker 构建时 Azure DevOps 私有 nuget 存储库未经授权
- webassembly - 为什么 0x83 0x00 格式良好的 3 编码为 Wasm 中的 u8?
- python - Conda 环境:打印已安装软件包的许可证
- python - 如何不打印 cmd 输出?