Ruby on rails 如何删除句子中的单词数组?
我有一系列的停止词:Ruby on rails 如何删除句子中的单词数组?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一系列的停止词: myArray=[,“a”,“ago”,“allo”,“am”,“an”,“and”,“ani”,“ar”,“are”,“not”,“arent”,“as”,“ask”,“at”,“did”,“not”,“do”,“doe”,“will”,“be”,“best”,“better”] 我想从句子中删除匹配项: sentence.split.delete_if{|x| array.include?(x.downcase)}.join(' ') => "somethin
myArray=[,“a”,“ago”,“allo”,“am”,“an”,“and”,“ani”,“ar”,“are”,“not”,“arent”,“as”,“ask”,“at”,“did”,“not”,“do”,“doe”,“will”,“be”,“best”,“better”]
我想从句子中删除匹配项:
sentence.split.delete_if{|x| array.include?(x.downcase)}.join(' ')
=> "something hello"
str='A something and hello'
因此,它变成:
“你好”
1。我如何用ruby实现这一点?
2.如何对字符数组执行此操作(删除所有匹配字符)
以下是字符数组:
special = ["(",")","@","#","^"]
sentence.split.delete_if{|x| array.include?(x.downcase) || special.include?(x) }.join(' ')
[“(“,”),“@”,“#”,“^”]
在比较之前,您可能希望将所有单词降格,以去掉句首的“A”:
sentence.split.delete_if{|x| array.include?(x.downcase)}.join(' ')
=> "something hello"
如果有字符串数组,则更容易:
(sentence.split - array).join(' ')
=> "A something hello" # but note that this doesn't catch the "A"
要同时删除特殊字符,请执行以下操作:
special = ["(",")","@","#","^"]
sentence.split.delete_if{|x| array.include?(x.downcase) || special.include?(x) }.join(' ')
删除单词或短语的另一种方法是:
array.each do |phrase|
sentence.gsub!(/#{phrase}/,'')
end
我的解决方案:
stop_words = ["","a","ago","also","am","an","and","ani","ar","aren't","arent","as","ask","at","did","didn't","didnt","do","doe","would","be","been","best","better"]
output = %w(A something and hello) - stop_words
Tilo答案的一行变体,干净且不区分大小写(尽管它返回所有小写输出,这可能不适合所有用途):
在第二种情况下,您希望输出什么?谢谢!对于字符数组也有类似的方法吗?(删除了任何匹配的字符)@Tilo如果我不想删除像“谢谢”这样的单词,我在数组中的是[“谢谢”,…]我添加了一个示例,说明如何执行此操作-请参见我的回答结尾,但输入也应该是字符串..输出应该是另一个字符串,你应该在你的答案周围放一些描述性的文字来解释它在做什么。
(sentence.downcase.split - array).join(' ')