从字符串中删除某些集合中存在的单词

我想从字符串中删除某些集合中的单词。 一种方法是迭代这个集合并使用str.gsub("subString", "")删除特定的单词。 这种function是否已经退出?

示例字符串:

 "Hotel Silver Stone Resorts" 

集合中的字符串:

 ["Hotel" , "Resorts"] 

输出应该是:

 " Silver Stone " 

您可以使用Regexp::union构建多个模式的Regexp::union

 words = ["Hotel" , "Resorts"] re = Regexp.union(words) #=> /Hotel|Resorts/ "Hotel Silver Stone Resorts".gsub(re, "") #=> " Silver Stone " 

请注意,您可能不得不逃避您的言论。

你可以在ruby中从另一个数组中减去一个数组。 结果是第一个数组中的所有元素都从第二个数组中删除。

在空格上拆分字符串,在一次快速移动中删除所有额外的单词,重新加入句子。

 s = "Hotel Silver Stone Resorts" junk_words = ['Hotel', 'Resorts'] def strip_junk(original, junk) (original.split - junk).join(' ') end strip_junk(s, junk_words) # => "Silver Stone" 

看起来肯定更好(我的眼睛)。 不确定性能特征(懒得对它进行基准测试)

我不知道你想要什么,但据我所知

 sentence = 'Hotel Silver Stone Resorts' remove_words = ["Hotel" , "Resorts"] # you can add words to this array which you wanted to remove sentence.split.delete_if{|x| remove_words.include?(x)}.join(' ') => "Silver Stone" 

要么

如果你有一个字符串数组,它会更容易:

 sentence = 'Hotel Silver Stone Resorts' remove_words = ["Hotel" , "Resorts"] (sentence.split - remove_words).join(' ') => "Silver Stone" 

你可以尝试不同的东西,但我不知道它是否会更快(取决于你的字符串和设置的长度)

 require 'set' str = "Hotel Silver Stone Resorts" setStr = Set.new(str.split) setToRemove = Set.new( ["Hotel", "Resorts"]) modifiedStr = (setStr.subtract setToRemove).to_a.join " " 

产量

 "Silver Stone" 

它使用Set类,它更快地检索单个元素(基于Hash构建)。 但同样,如果你的字符串/集非常大,那么使用to_a进行底层转换可能无法提高速度。

它还隐式删除字符串和集合中的重复项(当您创建集合时)