【问题标题】:I want a more efficient answer with these methods only我只想用这些方法得到更有效的答案
【发布时间】:2018-11-28 01:43:03
【问题描述】:

在过去的两周里,我一直在自学 Python。今天,我遇到了一个问题,我有一个非常烦人的解决方案(我为必须阅读它的人感到难过)。所以首先,我将介绍这个问题和我的解决方案。

问题:完成 getHost() 函数,该函数接受一个表示 URL 的字符串参数并返回一个字符串,该字符串与 响应主机名的倒数第二部分。例如,给定 URL“http://www.example.com/”,函数

将返回字符串“example”。给定 URL“ftp://this.is.a.long.name.net/path/to/some/file.php”,该函数将 返回字符串“名称”。虽然 URL 的路径和文件名部分是可选的,但您可以假设完整的 主机名后面总是跟一个正斜杠(“/”)。

我的解决方案:

def getHost(x):
    newstring = ""
    listofx = []
    for i in range(len(x)):
        listofx.append(x[i])
    for j in range(2):
        a = listofx.index("/")
        listofx.reverse()
        for k in range(a+1):
            listofx.pop()
        listofx.reverse()
    b = listofx.index("/")
    for g in range(len(listofx)-b):
        listofx.pop()
    for t in range(listofx.count(".")-1):
        for o in range(listofx.index(".")+1):
            listofx.reverse()
            listofx.pop()
            listofx.reverse()
    for f in range(len(listofx)-listofx.index(".")):
        listofx.pop()
    for h in range(len(listofx)):
        newstring = newstring + listofx[h]
    print (newstring)

我讨厌我的解决方案,因为看看我使用了多少个 for 循环。我觉得我别无选择,因为字符串是不可变的。我希望有人可以向我展示使用 while 循环和 find()/rfind() 方法的解决方案。我不想继续将字符串转换为列表来解决这类问题。

【问题讨论】:

  • 写得很好的问题
  • 不回答您的问题,但urlparse 将有助于摆脱您的大部分代码,然后您可以获取主机名并将其拆分为 '.'。

标签: python string methods


【解决方案1】:

使用findrfind

def getHost(x):
    index1 = x.find('//')
    index2 = x.find('/', index1+2)
    index3 = x.rfind('.',index1+2, index2)
    return(x[:index3].split('.')[-1])

【讨论】:

    【解决方案2】:

    是的,有更好的(pythonic)方式

    def extract(data):
        print(data.split('/')[2].split('.')[-2])
    
    extract("http://www.example.com/")
    extract("ftp://this.is.a.long.name.net/path/to/some/file.php")
    

    输出(显然)

    example
    name
    

    【讨论】:

    • 我正在寻求一个包含 while 循环和方法 find() 和 rfind() 的解决方案。
    • 我想指出,很好的解决方案。
    【解决方案3】:

    假设你的 URL 总是有双斜杠,你可以使用类似下面的东西;

    url = "http://www.example.com/"
    
    url = url.split("/")
    url = url[2].split(".")
    getHost = url[-2]
    
    print(getHost)
    

    【讨论】:

    • file:/abc.def/ghiwwe.example.com 怎么样?
    • @khachik http://wwe.example.com 可以,但是文件路径不会,因为它不是以双斜杠开头
    【解决方案4】:

    其实更简单的版本不需要rfind

    def getHost(x):
        index1 = x.find('//')
        index2 = x.find('/', index1+2)
        return(x[:index2].split('.')[-2])
    
    
    
    print(getHost("ftp://this.is.a.long.name.net/path/to/some/file.php"))
    print(getHost("http://www.example.com/"))
    

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多