Skip to content

Video editing with Python

Added encoding optional parameter to subtitle file loading feature (#1043)

Alekz0523d3c613a0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3f31bf6..ae1215e1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Support removed for Python versions 2.7, 3.4 & 3.5 [#1103, #1106]
### Added <!-- for new features -->
+- Optional `encoding` parameter in `SubtitlesClip` [#1043]
### Changed <!-- for changes in existing functionality -->
diff --git a/moviepy/video/tools/subtitles.py b/moviepy/video/tools/subtitles.py
index 25a23a0d..d0ae3974 100644
--- a/moviepy/video/tools/subtitles.py
+++ b/moviepy/video/tools/subtitles.py
@@ -20,6 +20,9 @@ class SubtitlesClip(VideoClip):
subtitles
Either the name of a file, or a list
+ encoding
+ Optional, specifies srt file encoding.
+ Any standard Python encoding is allowed (listed at https://docs.python.org/3.8/library/codecs.html#standard-encodings)
Examples
=========
@@ -28,18 +31,19 @@ class SubtitlesClip(VideoClip):
>>> from moviepy.video.io.VideoFileClip import VideoFileClip
>>> generator = lambda txt: TextClip(txt, font='Georgia-Regular', fontsize=24, color='white')
>>> sub = SubtitlesClip("subtitles.srt", generator)
+ >>> sub = SubtitlesClip("subtitles.srt", generator, encoding='utf-8')
>>> myvideo = VideoFileClip("myvideo.avi")
>>> final = CompositeVideoClip([clip, subtitles])
>>> final.write_videofile("final.mp4", fps=myvideo.fps)
"""
- def __init__(self, subtitles, make_textclip=None):
+ def __init__(self, subtitles, make_textclip=None, encoding=None):
VideoClip.__init__(self, has_constant_size=False)
if isinstance(subtitles, str):
- subtitles = file_to_subtitles(subtitles)
+ subtitles = file_to_subtitles(subtitles, encoding=encoding)
# subtitles = [(map(cvsecs, tt),txt) for tt, txt in subtitles]
self.subtitles = subtitles
@@ -144,7 +148,7 @@ class SubtitlesClip(VideoClip):
f.write(str(self))
-def file_to_subtitles(filename):
+def file_to_subtitles(filename, encoding=None):
""" Converts a srt file into subtitles.
The returned list is of the form ``[((ta,tb),'some text'),...]``
@@ -152,10 +156,11 @@ def file_to_subtitles(filename):
Only works for '.srt' format for the moment.
"""
+
times_texts = []
current_times = None
current_text = ""
- with open(filename, "r") as f:
+ with open(filename, "r", encoding=encoding) as f:
for line in f:
times = re.findall("([0-9]*:[0-9]*:[0-9]*,[0-9]*)", line)
if times: