【问题标题】:How do I read the variables of TextGrid file into Python?如何将 TextGrid 文件的变量读入 Python?
【发布时间】:2017-01-17 16:26:16
【问题描述】:

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

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 格式。怎么能继续为每个区间提取变量xminxmaxtext

编辑:

文件类型可以当作普通文本文件,逐行读取。这是我解决问题的方法。知道是否有一种特殊的方法可以从这些类型的文件中提取信息仍然很有趣。感谢您的回复。

【问题讨论】:

标签: python text


【解决方案1】:

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

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

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

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

第 7 行还表示文件的大小或项目数。

我们可以将这些数据重构为一个变量,如下所示:

有关组合字典和列表的更多信息,请参阅this

我建议您执行以下操作:

读取文件line by line。根据需要对前 7 行中的信息进行操作。在第 8 行创建项目数组,然后您可以检查是否存在“项目 [x]、类、名称、xmin、xmax、间隔:大小、间隔”并将它们分配到列表/字典的相关位置。如果您不太熟悉,请参阅 link 它很好地描述了数据结构。

然后您可以将值检索为

list[itemNumber]['class ']

list[itemNumber]['intervals'][intervalNumber-1]['xmin'] #index starts from 0

等等……

希望这会有所帮助。如果您需要任何进一步的帮助,请随时发表评论。

【讨论】:

  • 您好,感谢您的回复。我继续并将其保存为普通文本文件,手动删除我不需要的部分,并通过使用一堆 for 循环解决了:)
  • 太棒了。如果这只是一次性工作,那就更快了。
【解决方案2】:

您可以编写一个 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 文件中,你很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 2018-12-01
    • 2018-07-04
    • 2011-09-11
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多