【问题标题】:Python 3.2.2 Function Returns None on Non-Empty VariablePython 3.2.2 函数在非空变量上返回 None
【发布时间】:2011-10-29 22:31:35
【问题描述】:

我正在编写一个简单的脚本来下载 .mp4 TEDTalks 给定的 TEDTalk 网站链接列表:

# Run through a list of TEDTalk website links and download each
# TEDTalk in high quality MP4

import urllib.request

#List of website links
l = [
        "http://www.ted.com/index.php/talks/view/id/28",
        "http://www.ted.com/index.php/talks/view/id/29",
    ]

# Function which takes the location of the string "-480p.mp4",
# d = 1 less that location, and a string and returns the
# full movie download link
def findFullURL(d, e, s):
    a = s[d]
    if a != "/":
        #Subtract from d to move back another letter
        d = d - 1
        findFullURL(d, e, s)
    else:
        fullURL = "http://download.ted.com/talks/" + s[(d+1):e] + "-480p.mp4"
        #print(fullURL)
        return fullURL

#Iterate through a list of links to download each movie
def iterateList(l):
    for x in l:
        #get the HTML
        f = urllib.request.urlopen(x)
        #Convert the HTML file into a string
        s = str(f.read(), "utf-8")
        f.close()
        #Find the location in the string where the interesting bit ends
        e = s.find("-480p.mp4")
        d = e - 1
        #The problem is with this variable url:
        url = findFullURL(d, e, s)
        print("Downloading " + url)
        #TODO: Download the file

我确信 findFullURL 函数有效。如果您取消注释 findFullURL 函数末尾的 print(fullURL) 行,您将看到它完全按照我的需要输出下载链接。

但是,在我尝试通过url = findFullURL(d, e, s) 捕获该字符串的iterateList 函数中,变量url 似乎具有None 的值。我完全不明白这一点。它应该像以下示例一样简单,当我在解释器中尝试时,它可以工作:

def hello():
    return "Hello"
url = hello()
print(url)

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    我确信 findFullURL 函数有效。

    确定某段代码有效是浪费数小时调试时间寻找错误位置的最佳方式。

    事实上该功能不起作用。您错过了退货:

    def findFullURL(d, e, s):
        a = s[d]
        if a != "/":
            #Subtract from d to move back another letter
            d = d - 1
            return findFullURL(d, e, s)   # <<<<<<< here
        else:
            fullURL = "http://download.ted.com/talks/" + s[(d+1):e] + "-480p.mp4"
            #print(fullURL)
            return fullURL
    

    此外,您不应该使用递归来解决此任务。您可以改用rfind

    def findFullURL(d, e, s):
        d = s.rfind('/', 0, d + 1)
        # You probably want to handle the condition where '/' is not found here.
        return "http://download.ted.com/talks/" + s[(d+1):e] + "-480p.mp4"
    

    【讨论】:

    • 哦,哇!这是奇怪的行为。我以前从未在编程语言中看到过这种要求。这没有多大意义。我想我可以想到函数返回一个值给自己。
    • 感谢 rfind 的介绍。那会让我的任务更轻松。
    【解决方案2】:

    findFullURLif 语句的第一个分支上没有return 语句。在 Python 中,这意味着它返回 None

    【讨论】:

      猜你喜欢
      • 2018-08-14
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-25
      相关资源
      最近更新 更多