简体   繁体   中英

How to print keys and values from a text file

I have a file called "output.txt":

    "name": "abc",
    "age": 28,
    "name": "xxx",
    "age": 11,
    "name": "yyyb",
    "age": 15,

I want to read the file and print the name and age values on one line, one after the other:

abc 28
xxx 11
yyyb 15

The code I wrote is:

  file_data = {}
   object= File.open('output.txt', 'r') do |file|
   file.each_line do |line|  
   key,value = line  
   file_data[value] = key
   puts file_data

I am getting:

{nil=>"    \"name\": \"abc"\",\n"}
{nil=>"    \"age\": 28,\n"}
{nil=>"    \"name\": \"11"\",\n"}
{nil=>"    \"age\": false,\n"}
{nil=>"    \"name\": \"yyyb\",\n"}
{nil=>"    \"age\": 15,\n"}

The best way is to use some popular format like YAML or JSON so you can work with it using some library. Also you could achieve it with code like this:

file_data = ""
object= File.open('output.txt', 'r') do |file|
  file.each_line do |line|
    key, value = line.split(':').map{|e| e.strip.gsub(/(,|\")/,'')}
    file_data << (key == 'name' ? "#{value} " : "#{value}\n")
  end
end
puts file_data
File.read('output.txt')
    .split(/\s*,\s*/)
    .each_slice(2)
    .each do |name, age|
  puts [name[/(?<=: ").*(?=")/], age[/(?<=: ).*/]].join ' '
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM