我有一本单词词典,我想检查给定的字符串是否有这些单词。我希望它们存储在一个散列中,密钥是重复的单词,值是它发生的次数。
目前,它只会存储完整的字符串匹配(下面不算作包含单词low(,并且实际上不会增加重复的计数器。
给我指正确的方向?:(
dictionary = ["below","down","go","going","horn","how","howdy","it","i","low","own","part","partner","sit"]
def substringer(string, dict)
string_array = string.split(/W+/)
final_hash = {}
count = 0
dict.each do |entry|
if string_array.include?(entry)
final_hash = {entry => +1}
p final_hash
end
end
end
substringer("below, below, how's it goin?", dictionary)
结果
{"below"=>1}
{"how"=>1}
{"it"=>1}
这是我的"一个衬垫";解决方案:
dictionary = ["below", "down", "go", "going", "horn", "how", "howdy", "it", "i", "low", "own", "part", "partner", "sit"]
str = "below, below, how's it goin?"
str.split(/W+/).tally.slice(*dictionary) #=> {"below"=>2, "how"=>1, "it"=>1}
string_array.include?(entry)
返回true,无论该单词在给定数组中出现多少次。相反,使用string_array.count(entry)
,它会告诉你它出现的确切次数。
dict.each do |entry|
count = string_array.count(entry)
final_hash[entry] = count if count > 0
end
然而,这并不是最有效的方法,因为每个字典单词都需要遍历string_array一次(我认为string_aarray可能比dictionary大得多(。试着考虑一种在字符串数组上迭代的方法。
另外,考虑一下如何处理以大写字母开头的单词!
让我们反转代码并循环string_array
中的元素,然后检查是否包含在dict
中。
同样使用#each_with_object
构建散列,Hash.new(0)
创建一个散列,其中键的默认值为0
。
dictionary = ["below", "down", "go", "going", "horn", "how", "howdy", "it", "i", "low", "own", "part", "partner", "sit"]
def substringer(string, dict)
string_array = string.split(/W+/)
final_hash = string_array.each_with_object(Hash.new(0)) do |word, hsh|
hsh[word] += 1 if dict.include?(word)
end
p final_hash
end
测试:
substringer("below, below, how's it goin?", dictionary)
# {"below"=>2, "how"=>1, "it"=>1}
如果要评估多个字符串,我们可以编写以下内容。
require 'set'
dictionary = %w|
below down go going horn how howdy
it i low own part partner sit
|
DICTIONARY = dictionary.to_set
#=> #<Set: {"below", "down", "go", "going", "horn", "how", "howdy",
# "it", "i", "low", "own", "part", "partner", "sit"}>
def doit(str)
str.scan(/w+/).map(&:downcase).tally.select { |word| DICTIONARY.include?(word) }
end
doit "Below, below, how's it goin?"
#=> {"below"=>2, "how"=>1, "it"=>1}
doit "The sub's skipper said 'howdy' before going below then the sub went down below"
#=>{"howdy"=>1, "going"=>1, "below"=>2, "down"=>1}
请参阅String#扫描、Enumerable#计数和Hash#选择。
Set
查找非常快,特别是语句的执行
DICTIONARY.include?(word)