2013-05-30 71 views
0

我試圖編寫一個程序,該程序具有通過在文檔字符串中查找Author字符串來查找和打印文件作者的功能。我已經設法得到下面的代碼來打印一個文件的作者,該文件的作者字符串後面跟着作者姓名,作者字符串後面跟着一個名字。我遇到的問題是當作者字符串根本不存在時試圖打印Unknown,即文檔字符串的任何部分都不包含Author從docstring查找python文件的作者

N.B. lines只是在文件上使用readlines()構建的列表。

def author_name(lines): 
    '''Finds the authors name within the docstring''' 
    for line in lines: 
     if line.startswith("Author"): 
      line = line.strip('\n') 
      line = line.strip('\'') 
      author_line = line.split(': ') 
      if len(author_line[1]) >=4: 
       print("{0:21}{1}".format("Author", author_line[1])) 
      else: 
       print("{0:21}{1}".format("Author", "Unknown")) 

回答

0

如果您正在編寫函數,則返回一個值。不要使用打印(僅用於調試)。一旦你使用return,你可以,如果你找到筆者提前返回:

def author_name(lines): 
    '''Finds the authors name within the docstring''' 
    for line in lines: 
     name = 'Unknown' 
     if line.startswith("Author"): 
      line = line.strip('\n') 
      line = line.strip('\'') 
      author_line = line.split(': ') 
      if len(author_line[1]) >=4: 
       name = author_line[1] 
      return "{0:21}{1}".format("Author", name) # ends the function, we found an author 

    return "{0:21}{1}".format("Author", name) 

print(author_name(some_docstring.splitlines())) 

最後return語句只執行,如果有開始Author,因爲如果有,該功能會早日返回任何行。

另外,因爲我們默認nameUnknown,您可以使用break以及提前結束循環,離開返回最後一行:

def author_name(lines): 
    '''Finds the authors name within the docstring''' 
    for line in lines: 
     name = 'Unknown' 
     if line.startswith("Author"): 
      line = line.strip('\n') 
      line = line.strip('\'') 
      author_line = line.split(': ') 
      if len(author_line[1]) >=4: 
       name = author_line[1] 
      break # ends the `for` loop, we found an author. 

    return "{0:21}{1}".format("Author", name) 
+0

感謝,這正是我所需要的幫助 – jevans