Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

Parse of .txt on ruby

I would like to know how to do a parse of a txt with the following structure:

Each item in the file is separated by the TAB key.

The columns are:

purchaser name, item description, item price, purchase count, merchant address, merchant name.

purchaser name  item description    item price  purchase count  merchant address    merchant name
Jo?o Silva  R$10 off R$20 of food   10.0    2   987 Fake St Bob's Pizza
Amy Pond    R$30 of awesome for R$10    10.0    5   456 Unreal Rd   Tom's Awesome Shop
Marty McFly R$20 Sneakers for R$5   5.0 1   123 Fake St Sneaker Store Emporium
Snake Plissken  R$20 Sneakers for R$5   5.0 4   123 Fake St Sneaker Store Emporium

After analyzing this data I need to send to a normalized database and with the respective tables created.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use CSV for parsing files with separators, e.g.:

require 'csv'

CSV.foreach('your_file.txt', col_sep: "	", headers: true).map do |row|
  row.to_h
end
#=> [{"purchaser"=>"Jo?o", "name"=>"St", "item"=>"R$20", "description"=>"off" ...}, 
#    {"purchaser"=>"Amy", "name"=>"Rd", "item"=>"awesome", "description"=>"of", ..}, ...]

It seems like this data is ready to process. A more common way is using comma-separated value for files like this, so I would suggest you change file format if you can.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...