簡體   English   中英

計算 ruby 數組中的重復項並將計數存儲在 hash 中

[英]Counting duplicates in ruby array and storing count in hash

我有一本單詞詞典,我想檢查給定的字符串是否包含這些單詞中的任何一個。 我希望它們存儲在 hash 中,鍵是重復的單詞,值是它出現的次數。

目前,它只會存儲完整的字符串匹配(以下不計為包含單詞 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)返回真,不管這個詞在給定數組中出現了多少次。 相反,使用string_array.count(entry)它會告訴你它出現了多少次。

dict.each do |entry|
  count = string_array.count(entry)
  final_hash[entry] = count if count > 0
end

但是,這不是最有效的方法——因為您需要為每個字典單詞迭代一次 string_array(並且我假設 string_array 可能比字典大得多)。 嘗試考慮一種迭代字符串數組的方法。

另外,考慮如何處理以大寫字母開頭的單詞!

讓我們反轉您的代碼並循環遍歷string_array中的元素並檢查是否包含在dict中。

還使用#each_with_object構建 hash,並Hash.new(0)創建一個 hash,其中鍵的默認值為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#scanEnumerable#tallyHash#select

Set查找非常快,特別是語句的執行

DICTIONARY.include?(word)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM