Jump to content

[Solved] Output array to multiple text files?


Recommended Posts

So I have a single text file (Machines.txt) that contains the following data:

12345|This is a red machine                                                                     
23456|This is a white machine                                                                       
12|This is a blue machine                                                                   
de34qwe|This is a blue machine                                                                                                                                              
qwevsd|Machine color not identified                                                                         
pickles|This is a white machine                                                                     
hobart|This is a red machine                                                                    
taco|Machine color not identified

What I am hoping to do is read the text file and export just the machines names [Col0] to separate files based on the description [Col1]. So reading the data above would create and export to 4 different text files. The files would contain just the machine names, no descriptions.

For example:

Red.txt would have:

12345

hobart

White.txt would have:

23456

pickles

Blue.txt would have:

12

de34qwe

Unknown.txt would have:

qwevsd

tacos

As a start I found a function by UEZ which reads and parses the file, and I looked at _FileWriteFromArray but I'm not sure how to export one column based on another column.

Any suggestions or threads you can point me toward?

Thanks,

-Mike

Here is UEZ's function that I chose to parse the txt file:

#include <Array.au3>
$sText = FileRead(@ScriptDir & "\Machines.txt")
$aList = StringSplitW($sText, "|")

_ArrayDisplay($aList)

; #FUNCTION# ======================================================================================
; Name ................: StringSplitW()
; Version .............: v0.91 build 2012-10-06 beta
; Description .......: Splits a string into columns instead of rows as it is done by SplitString(), like a csv file to a 2d array ;-)
; Syntax ..............: StringSplitW($string, $delimiter, $max_width)
; Parameters ........: $string - string to split
; $delimiter - the delimter how to split the string
; Return values ....: Success - 2d array
; Failure 1 - either $string or $delimter is not set
; Failure 2 - array width exceeded
; Failure 3 - 2D array memory exceeded -> width + height > 0x5EFA
; Author ..............: UEZ
; Modified ............:
; Remarks ............:
; Related ..............: StringSplit()
; =================================================================================================
Func StringSplitW($string, $delimiter)
If $string = "" Or $delimiter = "" Then Return SetError(1, 0, 0)
Local $chk, $width, $i, $j, $k, $len, $max = 1, $max_width
Local $aPos[1], $l = 0
Local $aSplit = StringSplit($string, @LF)
$max_width = 0x5EFA - $aSplit[0]
If $max_width < 1 Then Return SetError(3, 0, 0)
Local $aVertical[$aSplit[0]][$max_width], $iDelimiterLen = StringLen($delimiter) - 1
For $k = 1 To $aSplit[0]
$len = StringLen($aSplit[$k])
If $len > 1 Then
$chk = StringReplace($aSplit[$k], $delimiter, $delimiter)
$width = @extended
If $width > $max_width Then Return SetError(2, 0, 0)
If $width >= $max Then $max = $width + 1
Switch $width
Case 0
$aVertical[$l][0] = $aSplit[$k]
Case Else
Dim $aPos[$width * 2 + 2]
$j = 1
$aPos[0] = 1
For $i = 0 To $width - 1
$aPos[$j] = StringInStr($aSplit[$k], $delimiter, 0, $i + 1) - 1
$aPos[$j + 1] = $aPos[$j] + 2 + $iDelimiterLen
$j += 2
Next
$aPos[UBound($aPos) - 1] = StringLen($aSplit[$k])
$j = 0
For $i = 0 To UBound($aPos) - 1 Step 2
$aVertical[$l][$j] = StringMid($aSplit[$k], $aPos[$i], $aPos[$i + 1] - $aPos[$i] + 1)
$j += 1
Next
EndSwitch
$l += 1
EndIf
Next
ReDim $aVertical[$l][$max]
Return $aVertical
EndFunc
Edited by mdwerne
Link to comment
Share on other sites

  • Moderators

mdwerne,

This shouldl do the trick: ;)

Global $sRed = "", $sWhite = "", $sBlue = "", $sUnknown = ""

$sFileText = "12345|This is a red machine" & @CRLF & _
             "23456|This is a white machine" & @CRLF & _
             "12|This is a blue machine" & @CRLF & _
             "de34qwe|This is a blue machine" & @CRLF & _
             "qwevsd|Machine color not identified" & @CRLF & _
             "pickles|This is a white machine" & @CRLF & _
             "hobart|This is a red machine" & @CRLF & _
             "taco|Machine color not identified"

; Split the file into lines
$aLines = StringSplit($sFileText, @CRLF, 1)
; And loop through them
For $i = 1 To $aLines[0]
    ; Split the line
    $aSplit = StringSplit($aLines[$i], "|")
    ; As long as there was a "|" on which to split
    If $aSplit[0] <> 1 Then
        ; See which group is involved
        If StringInStr($aSplit[2], "red") Then
        ; Add the name to the list
            $sRed &= $aSplit[1] & @CRLF
        ElseIf StringInStr($aSplit[2], "white") Then
            $sWhite &= $aSplit[1] & @CRLF
        ElseIf StringInStr($aSplit[2], "blue") Then
            $sBlue &= $aSplit[1] & @CRLF
        ElseIf StringInStr($aSplit[2], "red") Then
            $sRed &= $aSplit[1] & @CRLF
        Else
            $sUnknown &= $aSplit[1] & @CRLF
        EndIf
    EndIf
Next

; And display the lists - you can FileWrite here
MsgBox(0, "Red", $sRed)
MsgBox(0, "White", $sWhite)
MsgBox(0, "Blue", $sBlue)
MsgBox(0, "Unknown", $sUnknown)

All clear? :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

mdwerne,

This shouldl do the trick: ;)

Global $sRed = "", $sWhite = "", $sBlue = "", $sUnknown = ""

$sFileText = "12345|This is a red machine" & @CRLF & _
             "23456|This is a white machine" & @CRLF & _
             "12|This is a blue machine" & @CRLF & _
             "de34qwe|This is a blue machine" & @CRLF & _
             "qwevsd|Machine color not identified" & @CRLF & _
             "pickles|This is a white machine" & @CRLF & _
             "hobart|This is a red machine" & @CRLF & _
             "taco|Machine color not identified"

; Split the file into lines
$aLines = StringSplit($sFileText, @CRLF, 1)
; And loop through them
For $i = 1 To $aLines[0]
    ; Split the line
    $aSplit = StringSplit($aLines[$i], "|")
    ; As long as there was a "|" on which to split
    If $aSplit[0] <> 1 Then
        ; See which group is involved
        If StringInStr($aSplit[2], "red") Then
        ; Add the name to the list
            $sRed &= $aSplit[1] & @CRLF
        ElseIf StringInStr($aSplit[2], "white") Then
            $sWhite &= $aSplit[1] & @CRLF
        ElseIf StringInStr($aSplit[2], "blue") Then
            $sBlue &= $aSplit[1] & @CRLF
        ElseIf StringInStr($aSplit[2], "red") Then
            $sRed &= $aSplit[1] & @CRLF
        Else
            $sUnknown &= $aSplit[1] & @CRLF
        EndIf
    EndIf
Next

; And display the lists - you can FileWrite here
MsgBox(0, "Red", $sRed)
MsgBox(0, "White", $sWhite)
MsgBox(0, "Blue", $sBlue)
MsgBox(0, "Unknown", $sUnknown)

All clear? :)

M23

You beat me on the time! I was writing a similar function for him, but you shot first :D

Hi!

My UDF: NetInfo UDF Play with your network, check your download/upload speed and much more! YTAPI Easy to use YouTube API, now you can easy retrive all needed info from a video. NavInfo Check if a specific browser is installed and retrive other usefull information. YWeather Easy to use Yahoo Weather API, now you can easily retrive details about the weather in a specific region. No-IP UDF Easily update your no-ip hostname(s).

My Script: Wallpaper Changer Change you wallpaper dinamically, you can also download your wallpaper from your website and share it with all!   My Snippet: _ImageSaveToBMPConvert an image to bmp format. _SciteGOTO Open a file in SciTE at specific fileline. _FileToHex Show the hex code of a specified file

Link to comment
Share on other sites

#include <file.au3>
#include <array.au3>
Local $hFile = "C:\Dir\To\TextFile.txt", $aStrings, $aSplit, $aColorSplit
Local $sCname, $sColor = "", $sOutFile
_FileReadToArray($hFile, $aStrings)
For $string in $aStrings
  $aSplit = StringSplit($string, "|")
  for $i = 1 to 2
    $aSplit[$i] = StringStripWS(StringStripCR($aSplit[$i]), 7))
  next
  $sCname = $aSplit[1]
  if not StringInStr($aSplit[2], "color not identified")
    $aColorSplit = StringSplit($aSplit[2], " ")
    $sColor = $aColorSplit[3]
  else
    $sColor = "unknown"
  endif
  $hOutFile = $sColor & ".txt"
  FileWrite($hOutFile, $sCname & @CRLF)
next

Edited by Mechaflash
Spoiler

“Hello, ladies, look at your man, now back to me, now back at your man, now back to me. Sadly, he isn’t me, but if he stopped using ladies scented body wash and switched to Old Spice, he could smell like he’s me. Look down, back up, where are you? You’re on a boat with the man your man could smell like. What’s in your hand, back at me. I have it, it’s an oyster with two tickets to that thing you love. Look again, the tickets are now diamonds. Anything is possible when your man smells like Old Spice and not a lady. I’m on a horse.”

 

Link to comment
Share on other sites

Here my version:

 

#include <Array.au3>
$sText = FileRead(@ScriptDir & "\Machines.txt")
$aList = StringSplitW($sText, "|")

Global $sRed, $sWhite, $sBlue, $sUnknown
For $i = 0 To UBound($aList) - 1
    Switch StringStripWS(StringRegExpReplace($aList[$i][1], "(?i)This is a (red|white|blue) machine", "$1"), 3)
        Case "red"
            $sRed &= $aList[$i][0] & @CRLF
        Case "white"
            $sWhite &= $aList[$i][0] & @CRLF
        Case "blue"
            $sBlue &= $aList[$i][0] & @CRLF
        Case Else
            $sUnknown &= $aList[$i][0] & @CRLF
    EndSwitch
Next

$hFile = FileOpen(@ScriptDir & "\Red.txt", 2)
FileWrite($hFile, $sRed)
FileClose($hFile)

$hFile = FileOpen(@ScriptDir & "\White.txt", 2)
FileWrite($hFile, $sWhite)
FileClose($hFile)

$hFile = FileOpen(@ScriptDir & "\Blue.txt", 2)
FileWrite($hFile, $sBlue)
FileClose($hFile)

$hFile = FileOpen(@ScriptDir & "\Unknown.txt", 2)
FileWrite($hFile, $sUnknown)
FileClose($hFile)

_ArrayDisplay($aList)
Exit

; #FUNCTION# ========================================================================================================================================
; Name .................:   StringSplitW()
; Description ..........:   Splits  a string into columns instead of rows as it is done by SplitString(), like a csv file to a 2d array ;-)
; Syntax ...............:   StringSplitW($sString, $sDelimiter, $iWidthLen)
; Parameters ...........:   $sString - string to split
;                           $sDelimiter - [optional] the delimter how to split the string
;                           $iWidthLen - [optional] length of the row (amount of columns - default is 256)
; Return values .......:    Success - 2d array
;                           Error 1 - either $sString or $delimter is not set
;                           Error 2 - array width exceeded
;                           Error 3 - error splitting string
;
; Version .............:    v0.96 build 2015-01-20 beta
; Author ..............:    UEZ
; Modified ............:
; Remarks .............:    RegEx take from http://stackoverflow.com/questions/4476812/regular-expressions-how-to-replace-a-character-within-quotes
; Related .............:    StringSplit, StringReplace, StringRegExpReplace, StringLen, StringStripCR
; ===================================================================================================================================================
Func StringSplitW($sString, $sDelimiter = ";", $sQuotationMark = '"', $sDummy = "¦", $iWidthLen = 256)
    If $sString = "" Or $sDelimiter = "" Then Return SetError(1, 0, 0)
    Local $chk, $iWidth, $i, $j, $k, $iLen, $iMax = 1, $iMaxWidth
    Local $aPos[1], $l = 0
    Local $aSplit =  StringSplit(StringStripCR($sString), @LF)
    If @error Then Return SetError(3, 0, 0)
    Local $aVertical[$aSplit[0]][$iWidthLen], $iDelimiterLen = StringLen($sDelimiter) - 1, $sLine
    For $k = 1 To $aSplit[0]
        $iLen = StringLen($aSplit[$k])
        If $iLen > 1 Then
            $sLine = StringRegExpReplace($aSplit[$k], '(?m)\' & $sDelimiter & '(?=[^' & $sQuotationMark & ']*' & $sQuotationMark & '(?:[^' & $sQuotationMark & '\r\n]*' & $sQuotationMark & '[^' & $sQuotationMark & ']*' & $sQuotationMark & ')*[^' & $sQuotationMark & '\r\n]*$)', $sDummy)
            $chk = StringReplace($sLine, $sDelimiter, $sDelimiter)
            $iWidth = @extended
            If $iWidth > $iWidthLen Then Return SetError(2, 0, 0)
            If $iWidth >= $iMax Then $iMax = $iWidth + 1
            Switch $iWidth
                Case 0
                    $aVertical[$l][0] = $sLine
                Case Else
                    Dim $aPos[$iWidth * 2 + 2]
                    $j = 1
                    $aPos[0] = 1
                    For $i = 0 To $iWidth - 1
                        $aPos[$j] = StringInStr($sLine, $sDelimiter, 0, $i + 1) - 1
                        $aPos[$j + 1] = $aPos[$j] + 2 + $iDelimiterLen
                        $j += 2
                    Next
                    $aPos[UBound($aPos) - 1] = StringLen($sLine)
                    $j = 0
                    For $i = 0 To UBound($aPos) - 1 Step 2
                        $aVertical[$l][$j] = StringMid(StringReplace($sLine, $sDummy, $sDelimiter), $aPos[$i], $aPos[$i + 1] - $aPos[$i] + 1)
                        $j += 1
                    Next
                EndSwitch
                $l += 1
        EndIf
    Next
    ReDim $aVertical[$l][$iMax]
    Return $aVertical
EndFunc

Br,

UEZ

Edited by UEZ

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Link to comment
Share on other sites

WOW, Christmass in March!!

Again, thank you all for your replies. The real data file will typically have less than 500 rows and the description is not as simple searching for red, white and blue...but it's close, so all of these examples should work just fine.

I will give them all a whirl and see which is the best fit.

All the best,

-Mike :geek:

Link to comment
Share on other sites

@mdwerne my code strips the 3rd word in the 2nd part of the string, so as long as the 'color' is the third word, it auto-creates the file using that word and inserts the name into the file.

Spoiler

“Hello, ladies, look at your man, now back to me, now back at your man, now back to me. Sadly, he isn’t me, but if he stopped using ladies scented body wash and switched to Old Spice, he could smell like he’s me. Look down, back up, where are you? You’re on a boat with the man your man could smell like. What’s in your hand, back at me. I have it, it’s an oyster with two tickets to that thing you love. Look again, the tickets are now diamonds. Anything is possible when your man smells like Old Spice and not a lady. I’m on a horse.”

 

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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...