Search code examples
praat

Read TextGrid labels into a Strings object in Praat


I am stuck trying to figure out how to read the strings from a textgrid which is open in the window but not saved to the hard disk as a raw text file. My goal is to manipulate the strings and save them later.

I want to do something like this but don't really understand how the syntax would work.

tG$ = selectObject: selected$("TextGrid")
stringID = Read Strings from tG

numberOfStrings = Get number of strings
for stringNumber from 0 to numberOfStrings
    selectObject: stringID
    line$ = Get string: stringNumber
...

Solution

  • You need to loop through the intervals in the TextGrid and use appendFileLine to output the labels to a text file. For example:

    # Your need to select the TextGrid manually, and it has only one tier (tier number 1)
    
    outputFile$ = "~/Desktop/output.txt"
    
    writeFile: outputFile$, ""                        ; start from an empty .txt
    
    numberOfIntervals = Get number of intervals: 1    ; (this is tier 1)
    
    for interval to numberOfIntervals
        label$ = Get label of interval: 1, interval
        if label$ != ""                               ; (we just want non-empty intervals)
            xmin = Get start time of interval: 1, interval
            xmax = Get end time of interval: 1, interval
            appendFileLine: outputFile$, "'label$''tab$''xmin''tab$''xmax'"
        endif
    endfor
    

    This script will output a .txt file with tab delimited values: label, xmin, xmax. You can change the appendFileLine arguments to your needs (tab$ is a predefined variable, which is... a tab).