【问题标题】:Parsing a .txt file to key/value pairs in Ruby将 .txt 文件解析为 Ruby 中的键/值对
【发布时间】:2015-01-23 18:06:08
【问题描述】:

我想知道是否有人可以帮助我并告诉我将以下文本(来自 .txt 文件)解析为键值对的最佳方法

我必须使用的文本是:

"This is the Question Line"
"This is the Answer Line"

然后它重复。对我来说,解析这些行以及它们之后的所有行并将它们与问题和答案键相关联的最简单方法是什么?

【问题讨论】:

  • 指定:我希望它返回:{Question => "This is the Question Line", Answer => "This is the Answer Line"}
  • 你试过什么?具体来说,您对其中的哪一部分有疑问?
  • 我已经尝试并且能够将整个文本文件作为字符串读取,但我无法雄辩地将正确的行与问题和答案键相关联。

标签: ruby parsing text hash


【解决方案1】:

你可以的

array = []
# open the file in read mode. With block version you don'r need to
# worry about to close the file by hand. It will be closed when the
# read operation will be completed.
File.open('path/to/file', 'r') do |file|
  # each_line gives an Enumerator object. On which I'm calling
  # each_slice to take 2 lines at a time, where first line is the
  # question, and the second one is the answer. 
  file.each_line.each_slice(2).do |question, answer|
    array << {'Question' => question, 'Answer' => answer}
  end
end

【讨论】:

    【解决方案2】:

    正确的 ruby​​ 方式可能是这样的:

    data = Hash[['Question','Answer'].zip File.read('input.txt').split("\n")]
    

    【讨论】:

      猜你喜欢
      • 2016-04-07
      • 2013-07-11
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 2016-10-29
      • 2017-08-07
      • 1970-01-01
      • 2020-10-02
      相关资源
      最近更新 更多