코딩 수업/파이썬 (업무자동화)
[파이썬] 자막 파일에서 대사만 남기기 예제 Python Example : Extracting Only Dialogue from Subtitle Files
Jade S.
2024. 1. 28. 17:30
728x90
반응형
예제 : 영화 자막 파일에서 대사만 남기고 정리하기
import re
def subtitle(input):
#시간 정보를 가지고 있는 행을 제거
time = re.compile(r'\d+\n\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}')
result_text = re.sub(time, '', input)
# <i> 태그와 하이픈(-) 제거
result_text = re.sub(r'<\/?i>|-', '', result_text)
# 여러 개의 연속된 빈 줄을 하나의 빈 줄로 대체
result_text = re.sub(r'\n\s*\n', '\n\n', result_text)
return result_text.strip()
# 사용 예시
ori = """
4
00:00:09,449 --> 00:00:11,836
<i>Dr. Eugene Porter
is a scientist,</i>
5
00:00:12,025 --> 00:00:14,556
and he knows exactly
what caused this mess.
6
00:00:18,329 --> 00:00:20,704
<i>We'll find another vehicle.
We'll go with them until we do.</i>
7
00:00:22,156 --> 00:00:23,894
<i>- What do you think?
- Let's go.</i>
"""
result = subtitle(ori)
print(result)
출력>
Dr. Eugene Porter
is a scientist,
and he knows exactly
what caused this mess.
We'll find another vehicle.
We'll go with them until we do.
What do you think?
Let's go.
추가 예제 : strip 함수 없이 처리하려면? (처음과 끝의 공백 문자 제거)
How can it be done without using the strip function?
result_text = re.sub(r'^\s*|\s*$', '', result_text)
- ^: 문자열의 시작
- \s*: 0개 이상의 공백 문자(스페이스, 탭, 개행문자 등)
- |: 논리적 OR
- \s*$: 문자열의 끝에 있는 0개 이상의 공백 문자
- ^\s*: 문자열의 시작에서 0개 이상의 공백 찾기
- |\s*$: 또는 문자열의 끝에서 0개 이상의 공백 찾기
728x90
반응형