【问题标题】:The fastest way to get a url inside a string在字符串中获取 url 的最快方法
【发布时间】:2019-03-30 12:24:21
【问题描述】:

我要检查数千个字符串,我需要获取包含instagram.com/p/的完整url

到目前为止,我都在使用这种方法:

msg ='hello there http://instagram.com/p/BvluRHRhN16/'
msg = re.findall(
            'http[s]?://?[\w/\-?=%.]+instagram.com/p/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
            msg)
print(msg)

但有些网址找不到。

我想获取所有类似以下的网址:

https://instagram.com/p/BvluRHRhN16/ https://www.instagram.com/p/BvluRHRhN16/ http://instagram.com/p/BvluRHRhN16/ https://www.instagram.com/p/BvluRHRhN16/ www.instagram.com/p/BvluRHRhN16/

我怎样才能以最快的方式获得这个结果?

【问题讨论】:

  • 为什么不直接捕获 http 之后的所有内容,然后将结果提供给 stdlib 中的 urlparser 以确保它是有效的 url

标签: python regex findall


【解决方案1】:
url = '''
'hello there http://google.com/p/BvluRHRhN16/ this is a test',
      'hello there https://www.instagram.com/p/BvluRHRhN16/',
      'hello there www.instagram.com/p/BvluRHRhN16/ this is a test',
      'hello there https://www.instagram.net/p/BvluRHRhN16/ this is a test'
'''

from urlextract import URLExtract

extractor = URLExtract()
urls = extractor.find_urls(url)
print(urls)

输出: ['http://google.com/p/BvluRHRhN16/', 'https://www.instagram.com/p/BvluRHRhN16/', 'www.instagram.com/p/BvluRHRhN16/', 'https://www.instagram.net/p/BvluRHRhN16/']

已编辑:过滤 url 的

filtered = ([item for item in urls if "instagram.com/p/" in item])

print(filtered)

输出: ['https://www.instagram.com/p/BvluRHRhN16/', 'www.instagram.com/p/BvluRHRhN16/']

【讨论】:

  • 他没有尝试提取所有 URL。只有具体的网址作为他的意图。
  • 编辑了上面的答案以过滤所需的上下文路径。
【解决方案2】:

我假设输入是一个包含 URL 的句子列表。希望这能有所帮助。

msg =['hello there http://google.com/p/BvluRHRhN16/ this is a test',
      'hello there https://www.instagram.com/p/BvluRHRhN16/',
      'hello there www.instagram.com/p/BvluRHRhN16/ this is a test',
      'hello there https://www.instagram.net/p/BvluRHRhN16/ this is a test'
     ]

for m in msg:
    ms = re.findall('(http.*instagram.+\/p.+|www.*instagram.+\/p.+)',m)
    print(ms)

编辑的正则表达式:

ms = re.findall('(http.*instagram\.com\/p.+\/|www.*instagram\.com\/p.+\/)',m)

【讨论】:

  • 这也将返回 url 之后的所有文本。例如,“你好 www.instagram.com/p/BvluRHRhN16/ 这是一个测试”返回:“www.instagram.com/p/BvluRHRhN16/ 这是一个测试”
  • 您好,我尝试将instagram 替换为google 并且它也会打印google 链接,它不应该.. 还有其他方法吗?
  • @Yusufsn 这工作得很好,但我面临的解决方案是:如果链接后有一个空格,然后是一个单词,它也会打印这个单词,例如如果刺痛是https://www.instagram.com/p/BvnyDjXnHl5/ hello there,它会打印链接加上你好
  • 我在我的机器上试过了,它和你的意图一样。查看并将正则表达式更改为已编辑的版本。如果输入为https://www.instagram.com/p/BvnyDjXnHl5/ hello there,则输出为https://www.instagram.com/p/BvnyDjXnHl5/
  • @Yusufsn 我在我的机器上试过,甚至在网上试过,但我在链接后得到hello there,尝试去repl.it/repls/BoringFlakyInfinity在线查看
猜你喜欢
  • 2011-09-12
  • 1970-01-01
  • 2015-10-19
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 2020-09-09
相关资源
最近更新 更多