0
# Subtitle Items
1
2
Individual subtitle manipulation through the SubRipItem class. Each subtitle item contains timing information, text content, positioning data, and supports various text processing and timing operations.
3
4
## Capabilities
5
6
### Item Creation
7
8
Create subtitle items from various sources and formats.
9
10
```python { .api }
11
class SubRipItem:
12
def __init__(self, index=0, start=None, end=None, text='', position=''):
13
"""
14
Create a new subtitle item.
15
16
Args:
17
index (int): Subtitle sequence number (default: 0)
18
start: Start time (SubRipTime or coercible, default: 0)
19
end: End time (SubRipTime or coercible, default: 0)
20
text (str): Subtitle text content (default: '')
21
position (str): Display position/coordinates (default: '')
22
"""
23
24
@classmethod
25
def from_string(cls, source):
26
"""
27
Parse subtitle item from string representation.
28
29
Args:
30
source (str): Complete subtitle item in SRT format
31
32
Returns:
33
SubRipItem: Parsed subtitle item
34
"""
35
36
@classmethod
37
def from_lines(cls, lines):
38
"""
39
Parse subtitle item from list of lines.
40
41
Args:
42
lines (list): List of strings representing subtitle lines
43
44
Returns:
45
SubRipItem: Parsed subtitle item
46
"""
47
48
@classmethod
49
def split_timestamps(cls, line):
50
"""
51
Split timestamp line into start time, end time, and position.
52
53
Args:
54
line (str): Timestamp line (e.g., "00:00:01,500 --> 00:00:05,000")
55
56
Returns:
57
tuple: (start_time_str, end_time_str, position_str)
58
"""
59
```
60
61
### Properties
62
63
Access and modify subtitle item properties.
64
65
```python { .api }
66
@property
67
def index(self):
68
"""
69
Subtitle sequence number.
70
71
Returns:
72
int: Index number in subtitle sequence
73
"""
74
75
@property
76
def start(self):
77
"""
78
Start time of subtitle.
79
80
Returns:
81
SubRipTime: Start timestamp
82
"""
83
84
@property
85
def end(self):
86
"""
87
End time of subtitle.
88
89
Returns:
90
SubRipTime: End timestamp
91
"""
92
93
@property
94
def text(self):
95
"""
96
Subtitle text content.
97
98
Returns:
99
str: Text content with formatting tags
100
"""
101
102
@property
103
def position(self):
104
"""
105
Display position/coordinates string.
106
107
Returns:
108
str: Position specification (e.g., "X1:40 X2:600 Y1:20 Y2:50")
109
"""
110
111
@property
112
def duration(self):
113
"""
114
Duration of subtitle (computed as end - start).
115
116
Returns:
117
SubRipTime: Duration of subtitle display
118
"""
119
120
@property
121
def text_without_tags(self):
122
"""
123
Text content with HTML/formatting tags removed.
124
125
Returns:
126
str: Plain text without markup tags
127
"""
128
129
@property
130
def characters_per_second(self):
131
"""
132
Reading speed metric based on character count and duration.
133
134
Returns:
135
float: Characters per second (0.0 if duration is zero)
136
"""
137
```
138
139
### Timing Operations
140
141
Modify subtitle timing and perform time-based calculations.
142
143
```python { .api }
144
def shift(self, *args, **kwargs):
145
"""
146
Adjust start and end times by offset or ratio.
147
148
Args:
149
*args: Positional time arguments (hours, minutes, seconds, milliseconds)
150
**kwargs: Named time arguments or ratio for proportional scaling
151
152
Supported kwargs:
153
hours (int): Hours to add
154
minutes (int): Minutes to add
155
seconds (int): Seconds to add
156
milliseconds (int): Milliseconds to add
157
ratio (float): Multiply times by this ratio
158
"""
159
```
160
161
### String Representation
162
163
Convert subtitle items to various string formats.
164
165
```python { .api }
166
def __str__(self):
167
"""
168
Convert to standard SRT format string.
169
170
Returns:
171
str: Complete subtitle item in SRT format
172
"""
173
```
174
175
### Comparison Support
176
177
SubRipItem supports comparison operations based on timing.
178
179
```python { .api }
180
# Comparison operators based on start time, then end time
181
item1 < item2 # item1 starts before item2
182
item1 <= item2 # item1 starts before or at same time as item2
183
item1 == item2 # item1 and item2 have same timing
184
item1 >= item2 # item1 starts at or after item2
185
item1 > item2 # item1 starts after item2
186
item1 != item2 # item1 and item2 have different timing
187
```
188
189
## Usage Examples
190
191
### Creating Subtitle Items
192
193
```python
194
import pysrt
195
196
# Create from scratch
197
item = pysrt.SubRipItem(
198
index=1,
199
start=pysrt.SubRipTime(0, 0, 1, 500), # 00:00:01,500
200
end=pysrt.SubRipTime(0, 0, 5, 0), # 00:00:05,000
201
text="Hello, World!"
202
)
203
204
# Create with position information
205
positioned_item = pysrt.SubRipItem(
206
index=2,
207
start={'seconds': 6},
208
end={'seconds': 10},
209
text="Bottom right text",
210
position="X1:400 X2:600 Y1:300 Y2:350"
211
)
212
213
# Parse from string
214
srt_text = """1
215
00:00:01,500 --> 00:00:05,000
216
Hello, World!"""
217
item = pysrt.SubRipItem.from_string(srt_text)
218
```
219
220
### Text Processing
221
222
```python
223
# Working with formatted text
224
item.text = "<i>Italic text</i> and <b>bold text</b>"
225
plain_text = item.text_without_tags # "Italic text and bold text"
226
227
# Multi-line subtitles
228
item.text = "First line\nSecond line\nThird line"
229
230
# Reading analysis
231
print(f"Reading speed: {item.characters_per_second:.2f} chars/sec")
232
```
233
234
### Timing Operations
235
236
```python
237
# Adjust timing
238
item.shift(seconds=2) # Delay by 2 seconds
239
item.shift(milliseconds=-500) # Advance by 0.5 seconds
240
item.shift(ratio=1.1) # Speed up by 10%
241
242
# Duration calculations
243
print(f"Duration: {item.duration}") # Show how long subtitle displays
244
print(f"Start: {item.start}") # Show start time
245
print(f"End: {item.end}") # Show end time
246
247
# Create item with specific duration
248
start_time = pysrt.SubRipTime(minutes=1)
249
duration = pysrt.SubRipTime(seconds=3, milliseconds=500)
250
item = pysrt.SubRipItem(
251
start=start_time,
252
end=start_time + duration,
253
text="3.5 second subtitle"
254
)
255
```
256
257
### Item Modification
258
259
```python
260
# Load and modify existing subtitles
261
subs = pysrt.open('movie.srt')
262
263
for item in subs:
264
# Uppercase all text
265
item.text = item.text.upper()
266
267
# Add prefix to all subtitles
268
item.text = f"[MOVIE] {item.text}"
269
270
# Remove HTML tags
271
if '<' in item.text:
272
item.text = item.text_without_tags
273
274
# Extend short subtitles
275
if item.duration.ordinal < 1000: # Less than 1 second
276
item.end += pysrt.SubRipTime(milliseconds=500)
277
278
subs.save('modified_movie.srt')
279
```
280
281
### Sorting and Comparison
282
283
```python
284
# Sort subtitles by timing
285
subtitle_list = [item3, item1, item2] # Out of order
286
subtitle_list.sort() # Now sorted by start time
287
288
# Find overlapping subtitles
289
for i, current in enumerate(subs[:-1]):
290
next_item = subs[i + 1]
291
if current.end > next_item.start:
292
print(f"Overlap detected between items {current.index} and {next_item.index}")
293
294
# Filter by timing criteria
295
long_subtitles = [item for item in subs if item.duration.ordinal > 5000] # > 5 seconds
296
short_subtitles = [item for item in subs if item.duration.ordinal < 1000] # < 1 second
297
```
298
299
### Advanced Text Processing
300
301
```python
302
import re
303
304
# Remove specific formatting tags
305
def clean_tags(text):
306
# Remove specific HTML tags but keep content
307
text = re.sub(r'</?[bi]>', '', text) # Remove bold/italic tags
308
text = re.sub(r'<font[^>]*>', '', text) # Remove font tags
309
text = re.sub(r'</font>', '', text)
310
return text
311
312
# Process all subtitles
313
for item in subs:
314
# Clean formatting
315
item.text = clean_tags(item.text)
316
317
# Fix common encoding issues
318
item.text = item.text.replace('’', "'") # Fix apostrophes
319
item.text = item.text.replace('“', '"') # Fix quotes
320
item.text = item.text.replace(' ', '"')
321
322
# Break long lines
323
if len(item.text) > 50 and '\n' not in item.text:
324
words = item.text.split(' ')
325
mid = len(words) // 2
326
item.text = ' '.join(words[:mid]) + '\n' + ' '.join(words[mid:])
327
```
328
329
### Positioning and Display
330
331
```python
332
# Create subtitles with specific positioning
333
top_subtitle = pysrt.SubRipItem(
334
start={'seconds': 10},
335
end={'seconds': 15},
336
text="Top of screen",
337
position="Y1:50 Y2:100" # Top positioning
338
)
339
340
bottom_subtitle = pysrt.SubRipItem(
341
start={'seconds': 10},
342
end={'seconds': 15},
343
text="Bottom of screen",
344
position="Y1:400 Y2:450" # Bottom positioning
345
)
346
347
# Multiple simultaneous subtitles (different positions)
348
subs = pysrt.SubRipFile()
349
subs.append(top_subtitle)
350
subs.append(bottom_subtitle)
351
subs.save('positioned_subtitles.srt')
352
```