Riempimento dell'output stampato dei dati tabulari
-
03-07-2019 - |
Domanda
So che questo è probabilmente molto semplice, ma ho alcuni dati come questo in un unico file:
Artichoke
Green Globe, Imperial Star, Violetto
24" deep
Beans, Lima
Bush Baby, Bush Lima, Fordhook, Fordhook 242
12" wide x 8-10" deep
che mi piacerebbe poter formattare in un bel tipo di tabella TSV, per assomigliare a questo:
Name | Varieties | Container Data
----------|------------- |-------
some data here nicely padded with even spacing and right aligned text
Soluzione
Questo è un esempio ragionevolmente completo che presuppone quanto segue
- Il tuo elenco di prodotti è contenuto in un file chiamato veg.txt
- I tuoi dati sono disposti su tre righe per record con i campi su righe consecutive
Sono un po 'indecente con le rotaie, quindi ci sono sicuramente modi migliori e più eleganti per farlo
#!/usr/bin/ruby
class Vegetable
@@max_name ||= 0
@@max_variety ||= 0
@@max_container ||= 0
attr_reader :name, :variety, :container
def initialize(name, variety, container)
@name = name
@variety = variety
@container = container
@@max_name = set_max(@name.length, @@max_name)
@@max_variety = set_max(@variety.length, @@max_variety)
@@max_container = set_max(@container.length, @@max_container)
end
def set_max(current, max)
current > max ? current : max
end
def self.max_name
@@max_name
end
def self.max_variety
@@max_variety
end
def self.max_container()
@@max_container
end
end
products = []
File.open("veg.txt") do | file|
while name = file.gets
name = name.strip
variety = file.gets.to_s.strip
container = file.gets.to_s.strip
veg = Vegetable.new(name, variety, container)
products << veg
end
end
format="%#{Vegetable.max_name}s\t%#{Vegetable.max_variety}s\t%#{Vegetable.max_container}s\n"
printf(format, "Name", "Variety", "Container")
printf(format, "----", "-------", "---------")
products.each do |p|
printf(format, p.name, p.variety, p.container)
end
Il seguente file di esempio
Artichoke Green Globe, Imperial Star, Violetto 24" deep Beans, Lima Bush Baby, Bush Lima, Fordhook, Fordhook 242 12" wide x 8-10" deep Potatoes King Edward, Desiree, Jersey Royal 36" wide x 8-10" deep
Ha prodotto il seguente output
Name Variety Container ---- ------- --------- Artichoke Green Globe, Imperial Star, Violetto 24" deep Beans, Lima Bush Baby, Bush Lima, Fordhook, Fordhook 242 12" wide x 8-10" deep Potatoes King Edward, Desiree, Jersey Royal 36" wide x 8-10" deep
Altri suggerimenti
Prova String # rjust ( larghezza)
:
"hello".rjust(20) #=> " hello"
Ho scritto una gemma per fare esattamente questo: http://tableprintgem.com
Nessuno ha menzionato il "più cool" / il modo più compatto - usando l'operatore %
- ad esempio: "% 10s% 10s " % [1, 2]
. Ecco un po 'di codice:
xs = [ ["This code", "is", "indeed"], ["very", "compact", "and"], ["I hope you will", "find", "it helpful!"], ] m = xs.map { |_| _.length } xs.each { |_| _.each_with_index { |e, i| s = e.size; m[i] = s if s > m[i] } } xs.each { |x| puts m.map { |_| "%#{_}s" }.join(" " * 5) % x }
si ottiene:
This code is indeed very compact and I hope you will find it helpful!
Ecco il codice reso più leggibile:
max_lengths = xs.map { |_| _.length } xs.each do |x| x.each_with_index do |e, i| s = e.size max_lengths[i] = s if s > max_lengths[i] end end xs.each do |x| format = max_lengths.map { |_| "%#{_}s" }.join(" " * 5) puts format % x end
un altro gioiello: https://github.com/visionmedia/terminal-table Terminal Table è un generatore di tabelle ASCII veloce e semplice, ma ricco di funzionalità, scritto in Ruby.
Ho una piccola funzione per stampare un array 2D come una tabella. Ogni riga deve avere lo stesso numero di colonne per funzionare. È anche facile modificare le tue esigenze.
def print_table(table)
# Calculate widths
widths = []
table.each{|line|
c = 0
line.each{|col|
widths[c] = (widths[c] && widths[c] > col.length) ? widths[c] : col.length
c += 1
}
}
# Indent the last column left.
last = widths.pop()
format = widths.collect{|n| "%#{n}s"}.join(" ")
format += " %-#{last}s\n"
# Print each line.
table.each{|line|
printf format, *line
}
end
Kernel.sprintf dovrebbe iniziare.