我正在解析日志文件并在 ruby 中逐行读取
我将得到 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