您的問題已回答,因此我想建議一種替代方法,使用Enumerable#group_by,這取決於所需的信息。
str = "Bill thought the other Bill should pay the bill or Sue should pay the bill"
就在最高頻率
如果你只是想出現的最大次數一個字的頻率,你可以編寫以下。
def calculate_word_frequency(content)
content.split.
group_by(&:itself).
map { |_, arr| arr.size }.
max
end
calculate_word_frequency str
#=> 3
Object#itself是在Ruby v2.2中引入的。對於早期版本,請將group_by(&:itself)
替換爲group_by { |e| e }
。
請注意,content.split
的效果與content.split /\s+/
的效果相同。
Word中使用最高頻率,它的頻率
如果,另外,你想知道哪個字有最大的頻率,修改上面如下。
def calculate_word_frequency(content)
content.split.
group_by(&:itself).
map { |word, arr| [word, arr.size] }.
max_by(&:last)
end
calculate_word_frequency str
# => ["the", 3]
案例冷漠
如果你想「條例」和「法案」被視爲同一個字,改變content.split
到content.downcase.split
或修改上面如下。
def calculate_word_frequency(content)
content.split.
group_by { |word| word.downcase }.
map { |word, arr| [word, arr.size] }.
max_by(&:last)
end
calculate_word_frequency str
#=> ["bill", 4]
否認標點符號
如果你想忽略標點符號,這樣做首先,如下所示。
def calculate_word_frequency(content)
content.delete(".,:;'\"?!").
downcase.
split.
group_by(&:itself).
map { |word, arr| [word, arr.size] }.
max_by(&:last)
end
str = "Bill said \"Bill, pay the bill!\" Bif said 'Sue' should've payed the bill."
calculate_word_frequency str
#=> ["bill", 4]
我真的很難理解這是應該做什麼。你知道你可以使用'array.each'遍歷數組,對吧?使用'while'和一個計數器是非常麻煩的做法。 – tadman
您可以提供樣本輸入和輸出嗎? 你的代碼有點混亂(而不是每個,camelCase和snake_case混合),並且不運行(highest_wf_count是未定義的)。也許你可以把它清理一下? –
什麼是line_number參數? –