¿Como bajarse la lista de Tascón por Internet? (IV)

Primer escrito de el 2006, pero tema viejo.
Ya algunos me han escrito en este blog que esta no es la lista de Tascón, sino otra lista que está siendo distribuida con información de quienes votaron, por quienes votaron, entre otras cosas. Tienen razón, esta tiene mucho más información.
Bueno, después de no tener tiempo para nada, al fin pude terminar de exportar la lista a un archivo CSV. El programa corrió de la siguiente manera (les coloqué un enlace a un blog interesante en donde pueden ver la opciones de el JDK. Algunas dan dolor de cabeza):
[josevnz@localhost kodegeek]$ java -cp /home/josevnz/sf/kodegeek/eclipse:/home/josevnz/sf/kodegeek/lib/javadbf-0.4.0.jar:. -server -Xms200m -Xmx300m -Xcomp com.kodegeek.blog.santaines.ExportSantaInesTables /home/josevnz/.wine/drive_c/MaiSanta/repdbf.dbf > $HOME/repdbf.txtY el código que hace la exportación, en este caso trivial (no optimizado, pero hace el trabajo ya que corrige un montón de problemas al exportar los datos, además de que el comando \copy de PostgreSQL es muy débil manejando errores):
1:package com.kodegeek.blog.santaines;Una vez exportados todos los archivos, efectuamos la carga de los datos la hice utilizando el comando "copy" de PostgreSQL:
2:
3:import java.io.InputStream;
4:import java.io.FileInputStream;
5:import java.io.IOException;
6:
7:import java.util.Date;
8:
9:import java.text.DecimalFormat;
10:import java.text.DateFormat;
11:import java.text.SimpleDateFormat;
12:
13:import java.util.regex.Pattern;
14:
15:import com.linuxense.javadbf.DBFReader;
16:import com.linuxense.javadbf.DBFField;
17:import com.linuxense.javadbf.DBFException;
18:
19:/**
20: * This programs prints the contents of the 'Santaines'
DBF file as a CSV file
21: * You can load the resulting files like this (use the
proper paths):
22: * \copy centros from '/home/josevnz/centros.txt' with delimiter '@' null as 'null'
23: *
24: * This app is not optimized, but it will let you to export
the data from the DBF files
25: * on a reasonable amount of times, without too many errors.
26: * <b>License: GPL</b>
27: *
28: * @author josevnz
29: * @version 1.0 - 12/18/2005
30: */
31:public final class ExportSantaInesTables {
32:
33: private static final String FAKE_DATE = "1800-01-01";
34:
35: private static final Pattern isAfloatPattern =
Pattern.compile("\\d+\\.0");
36:
37: private static final Pattern [] unwantedChars = new Pattern[5];
38:
39: private static final DecimalFormat decform =
40: new DecimalFormat();
41:
42: private static final DecimalFormat decform2 =
43: new DecimalFormat();
44:
45: private static final DateFormat dateform =
46: new SimpleDateFormat ("yyyy-MM-dd");
47:
48: public static final String SQL_NULL = "null";
49:
50: /**
51: * Command line processing.
52: * @param args args[0], The full path of the DBF file to read
53: */
54: public static void main(String[] args) throws Exception {
55:
56: if ( ! (args != null && args.length == 1) ) {
57: throw new
IllegalArgumentException("Provide the name of the file to process");
58: }
59:
60: unwantedChars[0] = Pattern.compile("\\p{Cntrl}");
61: unwantedChars[1] = Pattern.compile("\\P{Print}");
62: unwantedChars[2] = Pattern.compile("\uffff");
63: unwantedChars[3] = Pattern.compile("\uc722");
64: unwantedChars[4] = Pattern.compile("\\\\");
65:
66: decform.applyLocalizedPattern("#.#");
67:
68: decform2.applyLocalizedPattern("#");
69: decform2.setDecimalSeparatorAlwaysShown(false);
70: decform2.setMaximumFractionDigits(0);
71:
72: InputStream stream = null;
73: DBFReader dbf = null;
74: String csvSeparator = "@";
75:
76: if (System.getProperty("csv.separator") != null) {
77: csvSeparator = System.getProperty("csv.separator");
78: }
79:
80: try {
81: stream = new FileInputStream(args[0]);
82: dbf = new DBFReader(stream);
83: // Decide how to 'encode'
the field information while writting the CSV file
84: int fields = dbf.getFieldCount();
85: // Print a header with all the fields
86: if (System.getProperty("printHeader") != null) {
87: for (int i = 0; i < fields; i++) {
88: System.out.print(
dbf.getField(i).getName());
89: if (i < fields - 1) {
90: System.out.print(
csvSeparator);
91: }
92: }
93: System.out.println();
94: }
95:
96: // Prefetch the row types
97: byte [] types = new byte[fields];
98: for (int i = 0; i < fields; i++) {
99: types[i] = dbf.getField(i).getDataType();
100: }
101:
102: // Print the actual data
103: Object [] rows = null;
104: while ( (rows = dbf.nextRecord() ) != null) {
105: for (int i = 0; i < fields; i++) {
106: System.out.print(
107: encodeAsString(
rows[i], types[i], csvSeparator)
108: );
109: if (i < fields - 1) {
110: System.out.print(csvSeparator);
111: }
112: }
113: System.out.println();
114: }
115: } catch (DBFException dbfExp) {
116: throw dbfExp;
117: } catch (IOException ioExp) {
118: throw ioExp;
119: } finally {
120: if (stream != null) {
121: stream.close();
122: }
123: }
124:
125: }
126:
127: /**
128: * Fix the data output so PostgreSQL copy can load it. PostgreSQL
\copy is pretty dumb...
129: * @param token
130: * @param type
131: * @param csvSeparator
132: * @return The given token as a parsed String
133: */
134: private static String encodeAsString(Object token, byte type,
String csvSeparator) {
135: String encoded = null;
136: if (token == null) {
137: return SQL_NULL;
138: }
139: switch (type) {
140: case DBFField.FIELD_TYPE_C: // Encode chars
141: encoded = ((String) token).trim().replaceAll(csvSeparator, "");
142: if (! encoded.equals("")) {
143:
144:
145: for (int i = 0; i < unwantedChars.length; i++) {
146: encoded = unwantedChars[i].
matcher(encoded).replaceAll("");
147: }
148: } else {
149: encoded = SQL_NULL;
150: }
151: break;
152: case DBFField.FIELD_TYPE_L: // Booleans go "as is"
153: encoded = token.toString();
154: break;
155: case DBFField.FIELD_TYPE_D: // Encode date, format ISO 8601
156: if (token != null) {
157: encoded = "\"" + dateform.format( (Date) token) + "\"";
158: } else {
159: encoded = FAKE_DATE; // Fake a date
160: }
161: break;
162: case DBFField.FIELD_TYPE_N: // Field is numeric
163: /*
164: * Don't know how many decimal digits this field could
have and the Java libray
165: * doesn't provide that information.
166: * For that reason, if it has zero decimals it will be
truncated.
167: * All the numeric fields on the Santaines database are
of the type 'numeric',
168: * so some magic is required...
169: */
170: Double number = (Double) token;
171: if (! isAfloatPattern.matcher(token.toString()).matches()) {
172: encoded = "" + decform.format(
number.floatValue()).replaceAll(",", "");
173: } else { // Truncate the floating number, print it with no ','.
174: encoded = "" + decform2.format(
number.longValue()).replaceAll(",", "");
175: }
176: break;
177: default: // We should never reach this
178: throw new IllegalStateException("Unmanaged type
found: " + type);
179: }
180: return encoded;
181: }
182:} // End of class
santaines=# \copy patriot from '/home/josevnz/patriota.txt' delimiters '@'¿Que hay de los datos? Dado que esta base de datos va a ser de sólo lectura, estoy revizando como crear ciertos indices para optimizar el accesso. Lo otro es que tengo que sentarme un rato a escribir el código para hacer algunas preguntas, entre esas la calidad de los datos.
\.
santaines=# select count(*) from patriot;
count
---------
2423094
(1 row)
Ya en su momento colocaré el código en CVS, por ahora prefiero concentrame en ver que tantas cosas tiene esta lista adentro.
Buscar en Technorati: Santaines



2 Comentarios:
no entendi nada como podemos hacer los neofitos en informatica, yo creo que todos tenemos derecho a revisar esa lista, por favor una explicacion mas facil...gracias
Anonimo (y quienes comparten la misma idea):
- La lista no va a estar disponible para ser bajada en este blog.
- No te preocupes si no entendiste nada del código, ya que no estaba pensando en ti cuando escribí el articulo
Enlaces a este articulo:
Crear un vínculo
<< Regresar