#--*-- coding: utf-8 --*--

def readLinesFromFile(filename):
    f = open(filename)
    lines = f.readlines()
    f.close()
    return lines

def writeLinesToFile(filename, lines):
    f = open(filename,'w')
    for line in lines:
        f.write(str(line[0]) + ' ' + str(line[1]) + ' ' + str(line[2]) + '\n')
    f.close()

def thirdColumnMerge(lines):
    '''
        由第三列元素是否相同合并列表
        如[[0,1,'A'],[2,3,'A'],[3,4,'A'],[5,6,'B']]
        合并成:[[0,4,'A'],[5,6,'B']]
    '''
    newLines = []
    t = lines[0][:]
    for line in lines:
        if t[2] != line[2]:
            newLines.append(t)
            t = line[:]
        else:
            t[1] = line[1]
    return newLines

def useTimeInfListFilter(lines, timeInfList = []):
    '''
        过滤
    '''
    Lines_new = []
    wt = 0
    for line in lines:
        l = float(line[0])
        r = float(line[1])
        while wt < len(timeInfList):
            if timeInfList[wt][0] <= l and timeInfList[wt][1] <= l:
                wt += 1
            elif timeInfList[wt][0] > l:
                if r <= timeInfList[wt][0]:
                    Lines_new.append([l,r,line[2]])
                    break
                elif r <= timeInfList[wt][1]:
                    Lines_new.append([l,timeInfList[wt][0],line[2]])
                    break
                else:
                    Lines_new.append([l,timeInfList[wt][0],line[2]])
                    l = timeInfList[wt][1]
                    wt += 1
            else:
                if r <= timeInfList[wt][1]:
                    break
                else:
                    l = timeInfList[wt][1]
                    wt += 1
    return Lines_new

timeInfList = []    #用于存储全部时间信息列表
for line in readLinesFromFile('changchun_2.asr'):
    data = line.split()
    if(data[-1] == 'sil'):
        timeInfList.append([float(data[1])/100.0,(float(data[2])+float(data[1]))/100.0])

#print(timeInfList)
timeInfList.append([100000.0,100000.0]) #增加结束标志

segLines = readLinesFromFile('changchun_2.seg')
#去掉所有所有第三列为'0'的
segLines = [d.split() for d in segLines if d.split()[-1] != '0']

#使用时间信息列表过滤segLines得到segLines_new
segLines_new = useTimeInfListFilter(segLines, timeInfList)
#print(segLines_new)

#合并
segLines = thirdColumnMerge(segLines_new)

#print(segLines)
writeLinesToFile('segLines.txt',segLines)
    
textGridLines = readLinesFromFile('changchun_2.TextGrid')
#去掉所有所有第三列为'""'的
textGridLines = [d.split() for d in textGridLines if d.split()[-1] != '""']
#print(textGridLines)
#使用时间信息列表过滤textGridLines得到textGridLines_new
textGridLines_new = useTimeInfListFilter(textGridLines, timeInfList)
#print(textGridLines_new)
#合并
textGridLines = thirdColumnMerge(textGridLines_new)

#print(textGridLines)
writeLinesToFile('textGridLines.txt',textGridLines)


