python - 使用 Python 替代品确定链接协议(protocol)

标签 python regex parsing

我需要找到确定用于访问特定链接的协议(protocol)的最佳方法。输入:字符串链接地址(以protocol://...开头)

这是我发现实现必要功能最方便的方法:

def detectProtocol(url):
    ind = url.find("://")
    return url[0:ind] if (ind != -1) else 'default_prot'

但我对从性能角度来看最好的方法很感兴趣。也许使用 re 匹配会更好? (但不是那么用户友好)

提前致谢!

附言如果您有自己的替代方案,欢迎分享

最佳答案

性能比较

这种比较忽略了所用功能的稳定性和协同效应等其他方面。例如,urlparse 提供的信息不仅仅是方案,因此可用于为其他需求提供数据。

Python 2.7.11+

Testing detect_protocol_by_index
1.56482505798
Testing detect_protocol_by_urlparse
9.13317012787
Testing detect_protocol_by_regex
3.11044311523

python 3.5.1+

Testing detect_protocol_by_index
1.5673476169999958
Testing detect_protocol_by_urlparse
15.466406801000176
Testing detect_protocol_by_regex
3.0660895540004276

来源

import sys 
import timeit
import re

if sys.version_info >= (3, 0): 
    from urllib.parse import urlparse
else:
    from urlparse import urlparse


def detect_protocol_by_index(url):
    ind = url.find("://")
    return url[0:ind] if (ind != -1) else 'default_prot'

def detect_protocol_by_urlparse(url):
    scheme = urlparse(url).scheme
    return scheme if scheme else 'default_prot'

regex = re.compile('^[^:]+(?=:\/\/)')
def detect_protocol_by_regex(url):
    match = regex.match(url)
    return match.group(0) if match else 'default_prot'

### TEST SETUP ###

test_urls = ['www.example.com', 'http://example.com', 'https://example.com', 'ftp://example.com']

def run_test(func):
    for url in test_urls:
        func(url)

def run_tests():
    funcs = [detect_protocol_by_index, detect_protocol_by_urlparse, detect_protocol_by_regex]
    for func in funcs:
        print("Testing {}".format(func.__name__))
        print(timeit.timeit('run_test({})'.format(func.__name__), setup="from __main__ import run_test, {}".format(func.__name__)))

if __name__ == '__main__':
    run_tests()

关于python - 使用 Python 替代品确定链接协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38540629/

相关文章:

python - 正则表达式匹配 [^a-z] 或 $

python - 如何在 Keras 中缓存层激活?

python - 调试 Python ANTLR4 语法

php - 如何正则表达式匹配一串数字和连字符,但不以连字符开头或结尾?

regex - 如何在JPQL中应用正则表达式?

python - 如何使用 lxml 访问评论

parsing - 使用 pest 时如何修复枚举缺失的文档?

python - 分水岭opencv后查找轮廓

python - 有效地将函数应用于神经元输出然后求和,而不是将函数应用于求和

python - 从变量和运算符的排列生成表达式