python-3.x 时间码标记计算

zbdgwd5y  于 2022-12-14  发布在  Python
关注(0)|答案(1)|浏览(180)

我是一个Python的初学者,我有一个小问题。有一个带有时间标记(小时:分钟:秒)的纯文本。“Some text 1”和“Some text 3”是广告。我需要计算文本中广告的总持续时间。如何做到这一点?
〈time=“08:00:00”〉〈type=ad〉部分文本1〈time=“08:02:24”〉〈/type=ad〉部分文本2〈time=“08:10:18”〉〈type=ad〉部分文本3〈time=“08:12:20”〉〈/type=ad〉

xwbd5t1u

xwbd5t1u1#

如果每个时间戳前面都有字符串,则应使用count方法(例如num = string.count("time="))查找字符串中出现的次数
然后,您可以在这个范围内使用for循环来查找实际的字符串。

  1. times = []
  2. index = 0
  3. for i in range(0, num):
  4. time = string.index("time=", index) # search for "time=", starting from index
  5. times.append(string[time+6:time+14])
  6. index = time+1

然后,您可以将字符串拆分为小时-分钟-秒整数字符串,如下所示:

  1. hms = [timestr.split(":") for timestr in times]

总之,下面的完整代码应该足够工作了

  1. string = '<time=”08:00:00"><type=ad> some text 1 <time=”08:02:24"></type=ad> some text 2 <time=”08:10:18"><type=ad> some text 3 <time=”08:12:20"></type=ad>'
  2. num = string.count("time=")
  3. times = []
  4. index = 0
  5. for i in range(0, num):
  6. time = string.index("time=", index) # search for "time=", starting from index
  7. times.append(string[time+6:time+14])
  8. index = time+1
  9. print(times)
  10. hms = [timestr.split(":") for timestr in times]
  11. print(hms)

如果您有任何疑问,请发表评论

展开查看全部

相关问题