Как можно оптимизировать скрипт Python?

Скрип выполняет соединение субтитров rus и eng.
f1 = open('file_eng.srt','r')
f2 = open('file_rus.srt','r')
fin = open('file_all.srt','w')
s = list(f1.readlines())
s1 = list(f2.readlines())
s3=[]
k=1
for i in s:
    for j in s1:
        if len(i)>4 and len(j)>4 and i==j and '00' in i and '00' in j:
            s3.append(str(k)+'\n')
            s3.append(i)
            k+=1
#print (s3)
l=2
k=0
j=1
while j<len(s):
    if (len(s[k])>4 and len(s[j])>4 or not s[k].replace('\n','').isdigit() and not s[j].replace('\n','').isdigit()) and '00' not in s[k] and s[k] not in s3[l-4:l]:
        #print (i.replace('\n',''))
        if (len(s[k])>4 and len(s[j])>4 or not s[k].replace('\n','').isdigit() and not s[j].replace('\n','').isdigit()) and '00' not in s[j]:
            s3.insert(l, s[j])
       # else:
       #     s3.insert(l, '.')
        s3.insert(l, s[k])

        l += 4
    k += 1
    j += 1
if (len(s[-1])>4 or not s[-1].replace('\n','').isdigit()) and '00' not in s[-1]:
    s3.append(s[-1])
    if (len(s[-2])>4 or not s[-2].replace('\n','').isdigit())and '00' not in s[-2]:
        s3.append(s[-2])

l=4
k=0
j=1
while j<len(s1):
    if (len(s1[k])>4 and len(s1[j])>4 or not s1[k].replace('\n','').isdigit() and not s1[j].replace('\n','').isdigit()) and '00' not in s1[k] and s1[k] not in s3[l-6:l]:
        #print (i.replace('\n',''))
        s3.insert(l, '\n')
        if (len(s1[k])>4 and len(s1[j])>4 or not s1[k].replace('\n','').isdigit() and not s1[j].replace('\n','').isdigit()) and '00' not in s1[j]:
            s3.insert(l, s1[j])
        #else:
        #    s3.insert(l, '.')
        s3.insert(l, s1[k])
        l += 7
    k += 1
    j += 1
if (len(s1[-1])>4 or not s1[-1].replace('\n','').isdigit()) and '00' not in s1[-1]:
    s3.append(s1[-1])
    if (len(s1[-2])>4 or not s1[-2].replace('\n','').isdigit())and '00' not in s1[-2]:
        s3.append(s1[-2])

for i in s3:
    fin.write(i)

f1.close()
f2.close()
fin.close()


Сделано наспех, сначала выдираем тайминги, после вставляем слова.
  • Вопрос задан
  • 2925 просмотров
Решения вопроса 1
JRazor
@JRazor
Senior StarkOverFlow Programmer
У вас не скрипт, а демонстрация unpythonic стиля. Сколько раз повторять - не используйте вы переменные m, n и прочее. В каждом учебнике уже пишут это. Как можно читать ваш код? Да никак!

По сабжу: не проще просто парсить каждую n-ую строку? Удаление лишнего RegExp'ом? Деление в список по "\n" и выборка только субтитров?
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
SolidlSnake
@SolidlSnake
Ваш дружелюбный сосед
Согласен, явно пришли из языка аля C\C++. :)

Цикл for можно (и нужно) использовать для обхода строк файлов:
# Нихт-нихт, не делайте так
f = open("bar.txt")
s = list(f1.readlines())
for i in  s:
   print i

# Я, я, зис ис гуд
f = open("foo.txt")
for l in f:
    print s


Условия if-операторов у вас тоже выглядят жутко, чрезмерно большие, прямо там производите замену - хотя можно это сделать аккуратно заранее.

Вообще, для красоты кода почитайте восьмой PEP (eng/rus), замечательная штука. :)
Ответ написан
@MagNet
Есть же уже готовое, зачем свой велосипед? Например: https://github.com/wistful/srtmerge
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы