Read a Text File as Strings and Truncate Them
【Question】
2010-8-13 991003 3166.63 3332.57 3166.63 3295.11
2010-8-10 991003 3116.31 3182.66 3084.2 3140.2
2010-8-9 991003 3085.44 3140.31 3084.33 3108.31
2010-8-7 991003 3203.14 3206.49 3136.42 3161.44
2010-8-6 991003 3138.6 3205.76 3128.1 3205.54
2010-8-3 991003 3114.36 3127.35 3063 3116.38
The above is a part of a txt file I want to read in (There ae hundreds of lines in it). I would like to read in data using readLine line by line and calculate the average of the last 4 columns for each line. For the first line, for example, I need to calculate average for 3166.63, 3332.57, 3166.63, 3295.11.
What I tried to do is reading data with readLine, get the target string using substring function and convert it to float type for the calculation. Since there are different numbers of spaces in the lines, the parameter value in the substring varies. But it’s impossible to pass values to the parameter manually for hundreds of lines. Is there any idea to do this in a simple way?
【Answer】
It’s simple to handle this in SPL (Structured Process Language), and then you can embed the SPL script in a Java application.
A |
|
1 |
=file("E:\\s.txt").read@n() |
2 |
=A1.(~.words@d()) |
3 |
=A2.(~.to(5,8).avg()) |
A1: Read in data line by line; each line makes a member of a sequence.
A2: Split each string member into a sequence of numbers.
A3: Get numbers from the 5th to the 8th from each of A2’s sequence member, which are the last 4 columns in the source text, and calculate average of the 4 numbers.
About the invocation of an SPL script in another application, see How to Call an SPL Script in Java.
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