如何将TextGrid文件的变量读入Python?

2024-09-19 20:31:13 发布

您现在位置:Python中文网/ 问答频道 /正文

余弦语言语料库的转录如下:

File type = "ooTextFile"
Object class = "TextGrid"

xmin = 0 
xmax = 3931.56874994773
tiers? <exists> 
size = 8
item []:
    item [1]:
        class = "IntervalTier"
        name = "Phrases"
        xmin = 0
        xmax = 3931.56874994773
        intervals: size = 1938
        intervals [1]:
            xmin = 0
            xmax = 3.59246613841739
            text = "Good morning"
        intervals [2]:
            xmin = 3.59246613841739
            xmax = 3.77632771424237
            text = "the dog likes me"
        intervals [3]:
            xmin = 3.77632771424237
            xmax = 8.15464058223137
            text = "fish swim"
        intervals [4]:
            xmin = 8.15464058223137
            xmax = 8.53678424963039
            text = "Sure."
        intervals [5]:
            xmin = 8.53678424963039
            xmax = 9.54622035219737
            text = "Just keep swimming"

文件采用.TextGrid格式。如何继续提取每个间隔的变量xminxmax和{}?在

编辑:

文件类型可以被视为普通文本文件并逐行读取。这是我解决问题的方法。如果有一种特殊的方法可以从这些类型的文件中提取信息,那还是很有趣的。谢谢你的回复。在


Tags: 文件方法text语言sizetypeitemclass
2条回答

在查看this是否有帮助之前,我没有使用过textGrid文件。如果它不是很容易写你自己的函数点这个。查看textGrid文件和示例文件here它显示这些文件有一套格式。在

•第1行和第2行->文件信息

•第3行->空白,分隔符

•第4-7行->其他信息

第7行还指示文件中的大小或项数。在

我们可以将这些数据重建为如下变量:

enter image description here

有关组合词典和列表的详细信息,请参见this。在

我建议你做以下事情:

读取文件line by line。按要求处理前7行中的信息。在第8行创建item数组,然后您可以检查“item[x],class,name,xmin,xmax,interval:size,interval”是否存在,并将它们分配到list/dict的相关位置。请看这个link如果您不太熟悉,它很好地描述了数据结构。在

然后,您可以将值检索为

list[itemNumber]['class ']

或者

^{pr2}$

等等。。。在

希望这有帮助。如果您需要进一步的帮助,请随时发表意见。在

您可以编写一个python脚本来执行此操作。我所做的是

with open('file.Textgrid','r') as f:
  data = f.read()
#print data #Use this to view how the code would look like after the program has opened the files
txttext = ''
for lines in data[9:]:  #informations needed begin on the 9th lines
  line = re.sub('\n','',line) #as there's \n at the end of every sentence.
  line = re.sub ('^ *','',line) #To remove any special characters
  linepair = line.split('=')
  if len(linepair) == 2:
    if linepair[0] == 'xmin':
       xmin == linepair[1]
    if linepair[0] == 'xmax':
       xmax == linepair[1]
    if linepair[0] == 'text':
       if linepair[1].strip().startswith('"') and linepair[1].strip().endswith('"'):
         text = linepair[1].strip()[1:-1]
         txttext += text + '\n'  

是的,使用write()函数将txtext保存到txt文件中,这样就很好了。在

相关问题 更多 >