我不熟悉编程和Python。你知道吗
背景
我的程序接受url。我想从url中提取用户名。你知道吗
用户名是子域。 如果子域是“www”,用户名应该是域的主要部分。域的其余部分应该丢弃(例如“.com/”、“.org/”)
我试过以下方法:
def get_username_from_url(url):
if url.startswith(r'http://www.'):
user = url.replace(r'http://www.', '', 1)
user = user.split('.')[0]
return user
elif url.startswith(r'http://'):
user = url.replace(r'http://', '', 1)
user = user.split('.')[0]
return user
easy_url = "http://www.httpwwwweirdusername.com/"
hard_url = "http://httpwwwweirdusername.blogger.com/"
print get_username_from_url(easy_url)
# output = httpwwwweirdusername (good! expected.)
print get_username_from_url(hard_url)
# output = weirdusername (bad! username should = httpwwwweirdusername)
我用strip()
、split()
和replace()
尝试了许多其他组合。你知道吗
你能告诉我如何解决这个相对简单的问题吗?你知道吗
有一个名为^{} 的模块专门用于此任务:
在
http://www.httpwwwweirdusername.com/
的情况下,它将输出不需要的www
。有一些解决方法可以忽略www
部分,例如,从分割的hostname
中获取不等于www
的第一个项:使用正则表达式可以做到这一点(可能会修改regex使其更精确/更高效)。你知道吗
这就产生了:
相关问题 更多 >
编程相关推荐