Created
May 7, 2012 20:42
-
-
Save mooreniemi/2630261 to your computer and use it in GitHub Desktop.
csv to array to txt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'date' | |
require 'csv' | |
class Post < | |
# a Person has a first name, last name, and city | |
Struct.new(:title, :link, :cats, :publish_date, :avg_rating, :comments, :votes, :username, :specialty, :pop) | |
end | |
# define an array to hold the all the posts of the week | |
posts = Array.new | |
#asks me what the file name for the week is and removes enter | |
csv = gets.chomp | |
# open csv file and then grab each field, skipping top row of field names | |
CSV.foreach(csv) {|fields| | |
if fields[0] == 'Post ID' then | |
next | |
end | |
# create a new Post constructor object | |
p = Post.new | |
#methods after field object to get rid of double-quotes and blanks | |
p.title = fields[1].tr_s('"', '').strip | |
p.link = fields[2].tr_s('"', '').strip | |
p.cats = fields[3].tr_s('"', '').strip | |
#taking the hours and minutes off the date field | |
date = fields[4].split(' ')[0] | |
#then convert that date variable to the ruby Date object | |
p.publish_date = Date.parse(date) | |
p.avg_rating = fields[5].tr_s('"', '').strip.to_f | |
p.comments = fields[7].tr_s('"', '').strip.to_i | |
p.votes = fields[9].tr_s('"', '').strip.to_i | |
p.username = fields[12].tr_s('"', '').strip | |
#for non-physician accounts a nil value of specialty appears which this skips | |
if fields[16].nil? then | |
next | |
end | |
p.specialty = fields[16].tr_s('"', '').strip | |
#puts the items p into the array posts | |
posts.push(p) | |
} | |
#puts posts - verified the array output | |
File.open("output.txt", 'w') do |f| | |
posts.each do |link, title, cats, username, publish_date, comments, votes| | |
f.puts %|<a href="#{p.link}"><strong>#{p.title}</strong></a> | |
<br>Summary space. | |
<br>Posted in #{p.cats} | |
<br>Authored by #{p.username} on #{p.publish_date} with #{p.comments} Comments and #{p.votes} Votes | |
| | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment