我正在创建一个程序,告诉Youtube视频在给定链接时链接到什么时间。当我只有一个链接时,我已经能够做我想要的了,但是如果给出一个文本正文,我想知道如何获取链接。
例如,如果输入为:
"This is filler to test the program, https://www.youtube.com/watch?feature=player_embedded&v=DkW5CSZ_VII#t=407 that is the link I want to pull out."
我怎样才能得到:
"https://www.youtube.com/watch?feature=player_embedded&v=DkW5CSZ_VII#t=407"
答案 0 :(得分:0)
您可以使用正则表达式:
import re
s = "This is filler to test the program, https://www.youtube.com/watch?feature=player_embedded&v=DkW5CSZ_VII#t=407 that is the link I want to pull out."
url = re.search("(http.+youtube\.com.+#t=\d+)", s).groups()[0]
但是一旦你使用re
,你就可以直接提取时间(最后将捕获组移动到\d+
,你也可以放弃捕捉http.+
1}}在开始时):
time = re.search("youtube\.com.+#t=(\d+)", s).groups[0]
请注意,此正则表达式无法在同一文本块中使用多个链接,这可能是个问题。您可以使用例如在线轻松测试正则表达式regex101