我正在编写一个脚本来搜索YouTube视频的元数据并从中获取时间码(如果有的话(。
with urllib.request.urlopen("https://www.googleapis.com/youtube/v3/videos?id=m65QTeKRWNg&key=AIzaSyDls3PGTAKqbr5CqSmxt71fzZTNHZCQzO8&part=snippet") as url:
data = json.loads(url.read().decode())
description = json.dumps(data['items'][0]['snippet']['description'], indent=4, sort_keys=True)
print(description)
这工作正常,所以我继续查找时间码。
# finds timecodes like 00:00
timeBeforeHour = re.findall(r'[d.-]+:[d.-]+', description)
>>[''0:00', '6:00', '9:30', '14:55', '19:00', '23:23', '28:18', '33:33', '37:44', '40:04', '44:15', '48:00', '54:00', '58:18', '1:02', '1:06', '1:08', '1:12', '1:17', '1:20']
它在 59:00 之后超越并抓取时间,但不正确,因为它错过了最后的":",所以我抓住了剩余的集合:
# finds timecodes like 00:00:00
timePastHour = re.findall(r'[d.-]+:[d.-]+:[d.-]+', description)
>>['1:02:40', '1:06:10', '1:08:15', '1:12:25', '1:17:08', '1:20:34']
我想连接它们,但仍然存在第一个正则表达式中时间不正确的问题。 如何阻止第一个正则表达式的范围超过一小时,即 59:59?
我看着正则表达式,我的头有点爆炸,任何澄清都会超级棒!
编辑:
我试过这个:
description = re.findall(r'?<!d:)(?<!d)[0-5]d:[0-5]d(?!:?d', description)
而这个:
description = re.findall(r'^|[^d:])([0-5]?[0-9]:[0-5][0-9])([^d:]|$', description)
但我输入错误。正则表达式的位置在做什么?
同样对于上下文,这是我尝试剥离的示例的一部分:
Nakedn1:02:40 Marvel 83' - Genesisn1:06:10 Ward-Iz - The Chasen1:08:15 Epoch - Formulan1:12:25 Perturbator - Night Businessn1:17:08 Murkula - Death Coden1:20:34 LAZERPUNK - RevengennPhotography by Jezael Melgoza"
使用
results = re.findall(r'(?<!d:)(?<!d)[0-5]?d:[0-5]d(?!:?d)', description)
请参阅正则表达式演示。
当不在单独的冒号分隔的数字字符串(如11:22:22:33
(内时,它将匹配时间字符串。
解释:
(?<!d:)
- 与前面不立即带有数字和:
的位置匹配的负面外观(?<!d)
- 与不紧接在数字前面的位置匹配的负后视(需要单独的后视,因为 Pythonre
后视仅接受固定宽度的模式([0-5]?d
- 从0
到5
的可选数字,然后是任意 1 位数字:
- 冒号[0-5]d
- 从0
到5
的数字,然后是任意 1 位数字(?!:?d)
- 与未紧跟可选:
和数字的位置匹配的负前瞻。
Python 在线演示:
import re
description = "Tracksn======n0:00 Tonebox - Frozen Coden6:00 SHIKIMO & DOOMROAR - Getawayn9:30 d.notive - Streets of Passionn14:55 Perturbator - Neo Tokyo"
results = re.findall(r'(?<!d:)(?<!d)[0-5]?d:[0-5]d(?!:?d)', description)
print(results)
# => ['0:00', '6:00', '9:30', '14:55']
我认为这就是您要查找的:
(^|[^d:])([0-5]?[0-9]:[0-5][0-9])([^d:]|$)
https://regex101.com/r/yERoPi/1