Storing Strings using For Loops

Hi, I am absolutely novice at this in general. My background is in mechanical engineering so only have had self-learning and an intro to C course. I am parsing a file of text that I get from my simulations and I am having trouble saving the all of the values. Instead I only have the final value after solving in a for loop. I’ve implemented it in so many ways from reading on my own and it has to be a simple fix.

First I tried doing the following :

readdir()
f = open("Cruciform/Post-Processing/hellothere.txt")
storelines = readlines(f)
close(f)

iter = 220
storage = []
for iter in 220:230
    iter +=  1
    initialRes = []
    if findnext("Solving for p", storelines[iter], 1) != nothing
        sst           = storelines[iter]
        findVal       = findfirst(r"\d\.\d\d\d\d\d", sst)
        initialRes    = sst[findVal];
        println("$initialRes");
    end        # empty as in do nothing
end
# SAMPLE OF TEXT FILE FOR REFERENCE
forces forceCoeffs1:
    Not including porosity effects
forceCoeffs forceCoeffs1:
    Not including porosity effects
Courant Number mean: 0.0226649 max: 11.448
Time = 0.001
PIMPLE: Iteration 1
smoothSolver:  Solving for Ux, Initial residual = 0.999998, Final residual = 0.0479853, No Iterations 2
GAMG:  Solving for p, Initial residual = 1, Final residual = 0.0580078, No Iterations 7
# END FILE EXCERPT OF LINES

The value was extracted from the last line extracted, but the for loop will not save all of the instances of “Solving for p” in the document, only the final iteration in the loop (I provided one instance in the sample text file but the line will appear 1000s of times). I decided let me trouble shoot the simpler method with just one specific line of the text file, say, for example line 225. So I re-wrote my code into this function and called a single line succesfully while catching errors

Cleaner attempt #2

function parseNumbers(inputLog,dataLot)
    storelines = readlines(inputLog)        # Take the file input and read
    storage = [ ]                            # temp storage
    # create condition to read pressure or break if error
    if findnext("Solving for p", storelines[dataLot], 1) != nothing
        sst           = storelines[dataLot]                                                # save lines to variable
        findVal       = findfirst(r"\d\.\d\d\d\d\d\d\d", sst)                         # filter lines
        initialRes    = sst[findVal];                                                        # combine the two methods
        store = parse(Float64, initialRes);                                           # create parse to convert strings
        return push!(storage, copy(store))                                           # push the value to storage
    else
        initialRes    = 0.0                                                                      # if theres an error just give 0
        return push!(storage, initialRes)
    end        
    close(inputLog)                                                                             # Close the original file
end
``
d = open("Cruciform/Post-Processing/hellothere.txt")     # open the text file
dataUse = 225                                                                 # line number in the text file to try on
testVar = parseNumbers(d,dataUse)                               # use our function

→ Then Julia provided me with the value of 0.050078. Great so now I figured I would write a simple for loop to do each entry from line 220 to 230 as a small step.

Implementation of my function in a For Loop

limits = 230
newstore = Vector{testVari}(undef, limits)
#newstore = [  ]
count = 0
for i in 220:limits
    dataStart = 220
    count += 1
    value = parseNumbers(d,dataStart)
    newstore[count]  = testVari(count, value)
    #push!(newstore, testVari)
    i += 1
end

This gives me the error: TypeError: in type, in parameter, expected Type, got a value of type Vector{Any}. If I uncomment push! and newstore = [ ] then I get a BoundsError: Attempt to access 0-element Vector string at index 220. This is rather easy for me on python but I really want to do it on Julia. Any advice, helpful tips and criticisms are welcomed. I’m clearly ignorant of some small detail!

please enclose your code snippet in triple `, like this:

```
my code
```

Thank you I just fixed it. I realized when you posted how horrendously awful it was without formatting

I would do it this way:

julia> a
"GAMG:  Solving for p, Initial residual = 1, Final residual = 0.0580078, No Iterations 7"

julia> m = match(r".*Initial residual =\s(.*),.*Final residual =\s(.*),", a);

julia> parse.(Float64, m.captures)
2-element Vector{Float64}:
 1.0
 0.0580078

guess work:

const f = eachline("Cruciform/Post-Processing/hellothere.txt")
let storage = Float64[]
for l in f
    if occursin("Solving for p", l)
        m = match(r".*Initial residual =\s(.*),.*Final residual =\s(.*),", l)
        init, final = parse.(Float64, m.captures)
        push!(storage, init)
    end
end

display(storage)
end
2 Likes

Hi jling, I’m very thankful for the help it has provided me. I have one question I have to use the REPL and save the preliminary answer in order to have it stored for plotting oddly enough. I tried running the code with the following below and I included an extra line where you can see I try to save the data and since I failed I provided another line to save “ans = [ ]”. What am I missing conceptually? I managed to plot the data anyways so I’m very thankful for the guidance.

using Plots

readdir()
f = open("Cruciform/Post-Processing/hellothere.txt")
storelines = readlines(f)
close(f)

let storage = Float64[]
    check = []
for l in storelines
    if occursin("Solving for p", l)
        m = match(r".*Initial residual =\s(.*),.*Final residual =\s(.*),", l)
        init, final = parse.(Float64, m.captures)
        push!(storage,init)
        push!(check,init)

    end
end
display(storage)
check = storage
end

save = ans
X = 1:300180
Y = save
plot(X,Y)

image

put these into the let ... end block and don’t use ans since it makes it hard to debug; sorry the indentation may have made it unclear

1 Like
using Plots

readdir()
f = open("Cruciform/Post-Processing/hellothere.txt")
storelines = readlines(f)
close(f)

let storage = Float64[]
for l in storelines
    if occursin("Solving for p", l)
        m = match(r".*Initial residual =\s(.*),.*Final residual =\s(.*),", l)
        init, final = parse.(Float64, m.captures)
        push!(storage,init)
        push!(check,init)

    end
end

display(storage)
X = 1:150090
Y = storage
plot(X,Y)

end

Success! Thank you Jling for spending the time to help me and teaching me some new tools. I have no one that programs to help me in person so this is one of the few times I turn to a forum and received such helpful guidance. I’m going to read into the structure a bit more to fully understand but I think I understand where I’m going wrong now!