-3

假设我有一个包含一些简单数据的文本文件:

elephant  dog
elephant  cat
elephant  dog
cat  dog
cat  elephant

我需要检查单词相互关联的频率并输出(大象和狗 2 次,大象和猫 2 次,猫和狗 1 次)。我该怎么做呢?

4

3 回答 3

1

撇开评论并理解这个问题和答案可能会被删除;-),我将提供以下内容:

pairs = string.lines.collect {|l| l.chomp.split('  ').sort.join(',')}  # eliminate ordering diffs
pairs.uniq.each {|p| puts "#{p} = #{pairs.count(p)}"}

http://rubyfiddle.com/riddles/a47c8

我提供这个是因为我认为标准和投票过程“需要工作”。

于 2013-07-01T16:44:03.607 回答
0
s = <<-end
elephant  dog
elephant  cat
elephant  dog
cat  dog
cat  elephant
end

ar = s.split("\n").map{|i| i.split}
# => [["elephant", "dog"],
#     ["elephant", "cat"],
#     ["elephant", "dog"],
#     ["cat", "dog"],
#     ["cat", "elephant"]]
ar.each_with_object({}){|i,h| h[i.sort] = ar.count{|j| i == j or i == j.reverse}}
# => {["dog", "elephant"]=>2, ["cat", "elephant"]=>2, ["cat", "dog"]=>1}
于 2013-07-01T20:18:52.830 回答
0
s = <<_
elephant  dog
elephant  cat
elephant  dog
cat  dog
cat  elephant
_

s.scan(/(\w+)\s+(\w+)/).map(&:sort).inject(Hash.new(0)){|h, pair| h[pair]+= 1; h}

结果:

{
  [
    "dog",
    "elephant"
  ] => 2,
  [
    "cat",
    "elephant"
  ] => 2,
  [
    "cat",
    "dog"
  ] => 1
}
于 2013-07-01T16:44:50.280 回答