from re import match def split_lyric(lyric_str): lyrics = [] temp_str = '' for index in range(len(lyric_str)): if lyric_str[index] == '[' and lyric_str[(index - 1) if index > 0 else index] != ']': lyrics.append(temp_str) temp_str = '' temp_str += lyric_str[index] if lyric_str[index] != '\n' else '' lyrics.append(temp_str) return lyrics[1:] def parse_lyric(lyric_str): total = {} lyrics = split_lyric(lyric_str) for lyric in lyrics: if not match(r'^(\[[a-zA-Z])', lyric): temp = lyric.replace('[', '').split(']') timestamps = temp[:-1] lyric = temp[-1].strip() for ts in timestamps: total[ts] = lyric sort = {} for k in sorted(total.keys()): sort[k] = total[k] return sort if __name__ == '__main__': with open('y.lrc', encoding='utf-8') as f: for k, v in parse_lyric(f.read()).items(): print(k, v)