ログファイルを解析し、Ruby で 1 行ずつ読み込んでいます
次のような2つの値を取得します。
iphone モバイル
モバイル iphone
キンドル アマゾン
アマゾン キンドル
つまり、両方の値が (a,b) と (b,a) のように交換されますが、1 としてカウントされ、次のような結果が必要です。
「iphone モバイル」 => 2
「kindle アマゾン」 => 2
ありがとうございました!
ここにうまくいくものがあります。入力行のソートされた配列がハッシュのキーとして使用されます。
#!/usr/bin/ruby
# Set the default value of the hash to be zero instead of nil
h = Hash.new 0
# Process each line of the input file
ARGF.each do |line|
# Split the line into a sorted array of words
values = line.chomp.split.sort
# Skip this line if there are no words on it
next if values.length == 0
# Increment the count for this array of words
h[values] += 1
end
# For each key in the hash
h.keys.each do |key|
# Join the words in the array with a space and print the count
puts "\"#{key.join(' ')}\" => #{h[key]}"
end