将 .txt 文件解析为 Ruby 中的 key/value 对
Parsing a .txt file to key/value pairs in Ruby
我想知道是否有人可以帮助我并告诉我将以下文本(来自 .txt 文件)解析为键值对的最佳方法
我必须处理的文本是:
"This is the Question Line"
"This is the Answer Line"
然后重复。对我来说解析这些行及其后的所有行并将它们与问答键相关联的最简单方法是什么?
你可以做到
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
正确的ruby方式可能是这样的:
data = Hash[['Question','Answer'].zip File.read('input.txt').split("\n")]
我想知道是否有人可以帮助我并告诉我将以下文本(来自 .txt 文件)解析为键值对的最佳方法
我必须处理的文本是:
"This is the Question Line"
"This is the Answer Line"
然后重复。对我来说解析这些行及其后的所有行并将它们与问答键相关联的最简单方法是什么?
你可以做到
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
正确的ruby方式可能是这样的:
data = Hash[['Question','Answer'].zip File.read('input.txt').split("\n")]