Jump to content

Parsing Text File


 Share

Recommended Posts

Hi there everyone,

I have a text file that looks something like the following:

Administrator        Guest               Matt                   
jaes                     james               jas                    
jasdfs               jasds               js                 
Matthew              pjaasddasdfs            pjaasdds               
pjads                pjdfs

Notice the odd formatting; there are not always a consistant amount of spaces between terms, I'm looking for a way to break up this text file into the individual terms (in this case user accounts), and not include the spaces. Any ideas?

Thanks for any advice!

Matt

Link to comment
Share on other sites

  • Moderators

If it's at least "consistant" with two or more spaces separating the columns, below will work.

The example returns a two dimensional array... rows ->[n][n]<- columns

#include <Array.au3> ; for _arraydisplay() func

Global $gs_somefile = "somefile_here.txt"
Global $ga_parsed = _myparse_filefunc($gs_somefile)

_ArrayDisplay($ga_parsed)

Func _myparse_filefunc($s_file)

    Local $s_fread = $s_file
    If FileExists($s_file) Then $s_fread = FileRead($s_file)

    If $s_fread = "" Then Return SetError(1, 0, 0)

    Local $a_lines = StringSplit(StringStripCR($s_fread), @LF)

    Local $a_col = 0
    Local $i_cols = 1, $i_rows = 0, $i_ub
    Local $a_wret[$a_lines[0] + 1][$i_cols]
    For $iline = 1 To $a_lines[0]
        If StringLen(StringStripWS($a_lines[$iline], 8)) = 0 Then ContinueLoop
        $a_col = StringRegExp($a_lines[$iline], "(?s)(.+?)(?:z|s{2,})", 3)
        If @error Then ContinueLoop
        $i_ub = UBound($a_col)
        If $i_ub > $i_cols Then
            $i_cols = $i_ub
            ReDim $a_wret[$a_lines[0] + 1][$i_cols]
        EndIf
        For $iword = 0 To $i_ub - 1
            $a_wret[$i_rows][$iword] = $a_col[$iword]
        Next
        $i_rows += 1
    Next

    If Not $i_rows Then Return SetError(2, 0, 0)

    ReDim $a_wret[$i_rows][$i_cols]
    Return $a_wret
EndFunc
Edited by SmOke_N

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...