【问题标题】:How to do text matching in .srt file and get the timestamp of the line in which the text exists如何在 .srt 文件中进行文本匹配并获取文本所在行的时间戳
【发布时间】:2019-07-26 06:59:03
【问题描述】:

返回值应该是那句话的开始时间。

import re

key = input("ENTER THE KEY PHRASE")
file = open('tcs.srt','r')

for line in file.readlines():
    if re.search(r'^%s'%key, line, re.I):
        print(line)

例如:

SERACH 密钥:milestone

可在以下位置找到: 0:01:25,299 --> 0:01:31,099 one of the significant milestones and great momentum in many of the areas that

0:01:25,299 应该在几秒钟内返回

【问题讨论】:

  • 您输入的字符串不清楚。
  • 我已经编辑了...请看一下
  • 您需要的正则表达式是 r"\d{1}\:\d{2}\:\d{2}\,\d{3}"。您可以稍后将其转换为时间戳。

标签: python regex file srt


【解决方案1】:

使用str.split 而不是正则表达式,您可以使用if key in line

例如:

import re

key = input("ENTER THE KEY PHRASE")
file = open('tcs.srt','r')

for line in file.readlines():
    if key in line:
        print(line.split()[0])

【讨论】:

  • 输出:输入关键词:里程碑再次
【解决方案2】:

.srt 文件包含时间戳和字幕。时间格式为hours:minutes:seconds,milliseconds。这是以秒为单位返回hours:minutes:seconds,milliseconds --> hours:minutes:seconds,milliseconds 中第一个时间戳的函数。

import re

def return_seconds(line):
    timeValues = line[:line.index("-->")].strip().replace(",",":").split(":")
    timeValues = list(map(int, timeValues))
    hours_to_seconds = timeValues[0] * 3600
    minutes_to_seconds = timeValues[1] * 60
    seconds = timeValues[2]
    milliseconds_to_seconds = round(timeValues[3]/1000, 2)
    total_seconds = hours_to_seconds + minutes_to_seconds + seconds + milliseconds_to_seconds
    return total_seconds

key = input("ENTER THE KEY PHRASE")
file = open('tcs.srt','r')

previousLine = ""

for line in file.readlines():
    if key in line:
        print("Starting seconds at line is {}".format(return_seconds(previousLine)))
    previousLine = line

【讨论】:

  • 感谢您的回复,但没有任何回复。
  • 问题是时间戳不在同一行文本中,它在每个文本的前一行,我如何修改代码。感谢您的帮助
  • @AKASHV 在这种情况下,我们需要获取上一行。我们可以将前一行保存在一个变量中,然后使用它进行计算。更新了答案。
  • 仍然没有输出
  • @AKASHV 抱歉,我认为您的正则表达式有效。它现在应该按预期工作。更新了答案。
【解决方案3】:

代码:

text="0:01:25,299 --> 0:01:31,099 one of the significant milestones and great momentum in many of the areas that"
import re
print(re.findall(r"\d{1}\:\d{2}\:\d{2}\,\d{3}",text))

输出:

['0:01:25,299', '0:01:31,099']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多