Hi all.
I’m have a fixed format file named “data.txt”:
10622431120301612015
10522431120301612015
10922431120301612015
10622431120301612015
10522431120301612015
10422431120301612015
10322431120301612015
10722431120301612015
10522431120301612015
10612431120301612015
10622431120301612015
10212431120301612015
10922431120301612015
10922431120301612015
10522431120301612015
10422431120301612015
Variables are described in the file “metadata.csv” (sorry, names are in italian. Posizione = position index; Lunghezza= length; Acronimovariabile = variable name; FormatoCampo = variable type)
“Posizione”;“Lunghezza”;“Acronimovariabile”;“FormatoCampo”
1;1;“sesso”;“String”
2;2;“classeEta”;“String”
4;1;“statoCivile”;“String”
5;3;“cittadinanza”;“String”
8;1;“continente”;“String”
9;2;“zona”;“String”
11;2;“regione”;“String”
13;3;“provincia”;“String”
16;1;“soggiornoLungoperiodo”;“String”
17;4;“anno”;“Int”
The following script uses ScottPJones solution and seems to work. It first reads the metadata, then creates a function “readData” that reads the data.
function createVectors(metadata)
for i in 1:size(metadata)[1]
nome = metadata[i,3]
tipo = metadata[i,4]
eval(parse(“$nome = Vector{$tipo}()”))
end
end
function createFunction(metadata)
out = “”“function readData(filename,metadata)
createVectors(metadata)
open(filename) do io
while true
line = readline(io)
line == “” && break
“””
for i in 1:size(metadata)[1]
inizio = parse(Int,metadata[i,1])
fine = parse(Int,metadata[i,1]) + parse(Int,metadata[i,2]) - 1
nome = metadata[i,3]
if metadata[i,4] == “String”
out = “$out \n push!($nome,strip(line[$inizio:$fine]))”
else
out = “$out \n push!($nome,parse(Int,strip(line[$inizio:$fine])))”
end
end
out = “$out \n end\n end\n end\n”
return(out)
end
metadata,variables= readdlm(“metadata.csv”,‘;’,String;header=true)
eval(parse(createFunction(metadata)))
readData(“data.txt”,metadata);
Reading David P. Sanders, “Creating domain-specific languages in Julia using macros” I’m convinced there are (much) better solutions, but I can’t find them.
Any suggestions?
Thank you
Guido