给出一个句子,我想统计名词类别(人与动物)出现的总次数。这与找出每个单词出现多少次不同。我也没有在寻找每个指定单词出现的总次数,而是寻找数组中所有指定单词出现的总数。在赞赏先进方法的同时,仍在寻找更简单的入门级编码。一个线性编码可能很棒,并受到真诚的赞赏,但我想对初学者有所了解。
句子“约翰和玛丽喜欢马,鸭和狗”。我想统计一下动物的数量(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 实际:未显示任何回报
答案 0 :(得分:2)
> str.scan(Regexp.union(animals)).size
# => 3
将正则表达式更改为
Regexp.new(animals.join("|"), true)
不区分大小写的匹配。
答案 1 :(得分:0)
您的代码一次只能输入一个字母:
"abcd"[0]
=> "a"
然后您的情况会将字母与单词进行比较:
"abcd"[0] == "duck"
# which is the same as:
"a" == "duck"
# which will never be true
您可以将字符串分成单词数组,并使用Array#count
和Array#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.")
要搜索单词内的匹配项,例如“斗牛犬”算作狗,可以使用:
def count_a(string)
ANIMALS.inject(0) { |count, animal| count + string.scan(animal).size }
end
答案 2 :(得分:0)
保持逻辑,像这样进行修复(请参阅嵌入式注释):
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