【问题标题】:How can I find a category of words in a string and take their tally in Ruby?如何在字符串中找到一类单词并在 Ruby 中记录它们?
【发布时间】:2018-12-21 09:43:55
【问题描述】:

给定一个句子,我想计算一个名词类别(人与动物)出现的总次数。这与找出每个单词出现的次数不同。我也不是在寻找每个指定单词出现的总次数,而是在一个数组中所有指定单词的总出现次数。虽然赞赏先进的方法,但正在寻找更简单、更初级的编码;一个班轮编码可能很棒并且受到真诚的赞赏,但我希望作为初学者有所了解。

在“约翰和玛丽喜欢马、鸭和狗”这句话中。我想统计动物的数量(3)。

str = "John and Mary like horses, ducks, and dogs."

animals= ["horses", "ducks", "dogs"]

def count_a(string)
  animals = 0
  i = 0
  while i < string.length  
    if (string[i]=="horses" || string[i]=="ducks" || 
      string[i]=="dogs")
      animals +=1
    end

    i +=1
  end
end
puts count_a(str)

预期:3 实际:没有显示任何回报

【问题讨论】:

标签: arrays ruby string


【解决方案1】:
> str.scan(Regexp.union(animals)).size
# => 3

将正则表达式更改为

Regexp.new(animals.join("|"), true)

用于不区分大小写的匹配。

【讨论】:

  • @AlekseiMatiushkin 谢谢,已编辑:)。不确定是否可以以任何理智的方式使联合不区分大小写。
  • 我可以想到 Regexp.new(Regexp.union(...), [1])/#{Regexp.union(...)}/i,但在我看来,这两个都不够理智。此外,劫持Regexp.union(...).options 似乎是不可能的。
【解决方案2】:

您的代码一次只运行一个字母:

"abcd"[0]
=> "a"

然后您的条件将该字母与单词进行比较:

"abcd"[0] == "duck"
# which is the same as:
"a" == "duck"
# which will never be true

您可以将字符串拆分为单词数组并使用Array#countArray#include? 来计算出现次数:

ANIMALS = ["horses", "ducks", "dogs"]

def count_a(string)
  string.split(/\b/).count { |word| ANIMALS.include?(word) }
end

puts count_a("John and Mary like horses, ducks, and dogs.")

要在单词中搜索匹配项,例如“bulldog”算作狗,您可以使用:

def count_a(string)
  ANIMALS.inject(0) { |count, animal| count + string.scan(animal).size }
end

【讨论】:

    【解决方案3】:

    保持你的逻辑,像这样修复(参见内联 cmets):

    def count_a(string)
      string = string.scan(/\w+/).map(&:downcase) # <------------ split into words
      animals = 0
      i = 0
      while i < string.length
        if (string[i]=="horses" || string[i]=="ducks" || 
          string[i]=="dogs")
          animals +=1
        end
        i +=1
      end
      return animals # <------------ return the count
    end
    
    puts count_a(str) #=> 3
    

    【讨论】:

      猜你喜欢
      • 2019-04-27
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 2011-09-05
      • 2019-06-30
      • 2018-09-02
      相关资源
      最近更新 更多