Parse a csv file having a primary-sub tables structure
We have a non-standard format csv file. Odd-numbered lines are records of the primary table – one line corresponding to one record, which consists of 3 fields: idUniversity, nameOfUniversity and noOfBuses, where the 3rd field is a redundant one for recording the number of corresponding records in the subtable represented by the even-numbered line. The even-numbered lines represent records of the subtable; each line has N items, and every two items correspond to one record, which has two fields: idBus and noOfBus.
1,Harvard University,2 1,140,2,56 2,Massachusetts Institute of Technology,2 1,240,5,56 3,University of California Berkeley,3 1,112,2,56,3,28 4,Columbia University,4 1,84,2,84,3,84,7,28 |
Task: Use Java to parse the primary-sub tables as a structure that is convenient for subsequent computations.
idUniversity |
nameOfUniversity |
noOfBuses |
|
1 |
Harvard University |
idBus |
noOfBus |
1 |
140 |
||
2 |
56 |
||
2 |
Massachusetts Institute of Technology |
idBus |
noOfBus |
1 |
240 |
||
5 |
56 |
||
3 |
University of California Berkeley |
idBus |
noOfBus |
1 |
112 |
||
2 |
56 |
||
3 |
28 |
||
4 |
Columbia University |
idBus |
noOfBus |
1 |
84 |
||
2 |
84 |
||
3 |
84 |
||
7 |
28 |
Write the SPL code:
1 |
=file("d:/data.csv").import@cw() |
2 |
=A1.group((#-1)\2) |
3 |
=A2.new(~1(1):idUniversity,~1(2):nameOfUniversity,~2.group((#-1)\2).new(~1:idBus,~2:noOfBus):noOfBuses) |
A1: Parse the csv file as a two-dimensional sequence separated by commas.
A2: Group the sequence every two rows.
A3: Parse the 1st row of each group as the primary table record, and parse the 2nd row as multiple subtable records and use them as the primary table fields.
The above SPL code establishes primary-sub table association, and we can use the dot to access the subtable. To access the subtable record whose idBus is greater than 2 in the 2nd primary table record, we can directly write the code as =A3(4).noOfBuses.select(idBus>2).
Read How to Call a SPL Script in Java to find how to integrate SPL into a Java application.
Source:https://stackoverflow.com/questions/71957483/parsing-comma-delimited-text-file-with-alternating-data-rows-using-the-java-stre
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProcSPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL