Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python 2.7中,以字符串形式将url缩短为域名_Python_Regex_Python 2.7 - Fatal编程技术网

在python 2.7中,以字符串形式将url缩短为域名

在python 2.7中,以字符串形式将url缩短为域名,python,regex,python-2.7,Python,Regex,Python 2.7,假设我有一根绳子 这是个好娃娃http://www.google.com/a/bs/jdd/etc/etc/a.py 我想要这样的东西 这是一个好娃娃www.google.com 我在python中尝试了print re.sub(r'(http://| https://),“”,a))函数,但我只能从中删除http://部分。关于如何在python 2.7中实现这一点的任何想法如果您想使用正则表达式,那么您可以这样做: >>> string = "This is a good

假设我有一根绳子
这是个好娃娃http://www.google.com/a/bs/jdd/etc/etc/a.py

我想要这样的东西
这是一个好娃娃www.google.com


我在python中尝试了
print re.sub(r'(http://| https://),“”,a))
函数,但我只能从中删除
http://
部分。关于如何在python 2.7中实现这一点的任何想法如果您想使用正则表达式,那么您可以这样做:

>>> string = "This is a good doll http://www.google.com/a/bs/jdd/etc/etc/a.py"
>>> print string.replace('http://', '').split('/')[0]
This is a good doll www.google.com
>>> import re
>>> the_string = "This is a good doll http://www.google.com/a/bs/jdd/etc/etc/a.py"
>>> def replacement(match):
...     return match.group(2)
... 
>>> re.sub(r"(http://|https://)(.*?)/\S+", replacement, the_string)
'This is a good doll www.google.com'

如果要使用正则表达式,则可以执行以下操作:

>>> import re
>>> the_string = "This is a good doll http://www.google.com/a/bs/jdd/etc/etc/a.py"
>>> def replacement(match):
...     return match.group(2)
... 
>>> re.sub(r"(http://|https://)(.*?)/\S+", replacement, the_string)
'This is a good doll www.google.com'

您可能需要添加正则表达式尝试使用url解析库来解析url并获取主机名。您可能需要添加正则表达式尝试使用url解析库来解析url并获取主机名。如果url后面有任何文本,这将不起作用,例如,请使用
string=“这是一个好娃娃http://www.google.com/a/bs/jdd/etc/etc/a.py lorem ipsum“
它应该首先将整个url与正则表达式匹配,并且仅对url进行匹配。如果url后面有任何文本,则此操作无效,例如,使用
string=“这是一个好玩偶”进行尝试http://www.google.com/a/bs/jdd/etc/etc/a.py 乱数假文“
它应该首先将整个url与正则表达式匹配,并且只在url上执行此操作。