【问题标题】:How to parse a text file and count occurance of a string?如何解析文本文件并计算字符串的出现次数?
【发布时间】:2014-04-08 08:00:00
【问题描述】:

我有一个包含日期列表的文本文件

2014-01-18
2014-01-18
2014-01-20
2014-01-20
2014-01-20
2014-01-21
2014-01-21
2014-01-22
2014-01-22
2014-01-22
2014-01-22
2014-01-22

如何计算每个日期记录了多少次?所以输出类似于:

2014-01-18 2
2014-01-19 0
2014-01-20 3
2014-01-21 2
2014-01-22 5

【问题讨论】:

  • 如果你只需要输出:sort textfile | uniq -c
  • 我同意@Stefan 的观点,即使用简单的 shell 命令行是最好的方法。它既快速又简单。

标签: ruby ruby-1.9.3


【解决方案1】:
path = '/path/to/file'
lines = File.readlines(path).map(&:chomp)

# At this point lines should look like below, this is just for testing
lines = ["2014-01-18", "2014-01-18", "2014-01-20", 
         "2014-01-20", "2014-01-20", "2014-01-21", 
         "2014-01-21", "2014-01-22", "2014-01-22", 
         "2014-01-22", "2014-01-22", "2014-01-22"]

# All Ruby versions (since you're using Ruby 1.9.3 you should use tihs)
Hash[ lines.group_by { |v| v }.map { |k, v| [k, v.size] } ]
# Ruby >= 2.1.0
lines.group_by { |v| v }.map { |k, v| [k, v.size] }.to_h

#=> {"2014-01-18"=>2, "2014-01-20"=>3, "2014-01-21"=>2, "2014-01-22"=>5}

【讨论】:

  • Hash.[] 是老式的。
  • 我也不喜欢它,但我不知道有其他选择;你会用什么?
  • 为什么不使用Array#to_h
  • @sawa 哦!我不知道,它似乎是在 Ruby 2.1.0 中引入的,谢谢你的信息! spuggy 我来写,你用的是哪个 Ruby 版本?
  • @spuggy 如果您使用旧版本的 Ruby,您应该通过添加相关标签在问题中表达这一点。
【解决方案2】:

我喜欢使用Hash.new

lines = ["2014-01-18", "2014-01-18", "2014-01-20", 
         "2014-01-20", "2014-01-20", "2014-01-21", 
         "2014-01-21", "2014-01-22", "2014-01-22", 
         "2014-01-22", "2014-01-22", "2014-01-22"]

result = Hash.new(0)
lines.each { |line| result[line] += 1 }

result
# => {"2014-01-18"=>2, "2014-01-20"=>3, "2014-01-21"=>2, "2014-01-22"=>5}

【讨论】:

  • 你不必通过一个块,只需result = Hash.new(0)
  • 还有一个较短的版本,因为我是一个单线人:lines.each_with_object(Hash.new(0)) { |l, h| h[l] += 1 }
  • @Stefan 你是对的,我通常使用更详细的块。我编辑了答案。
【解决方案3】:
lines = File.readlines('file.txt').map(&:chomp)

op = Hash.new(0)

lines.each do |line|
  op[line.to_sym] += 1
end

puts op.sort_by { |k, v| v }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 2011-10-08
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2017-03-02
    • 1970-01-01
    相关资源
    最近更新 更多