2013-05-30 3 views
0

docstring에서 Author 문자열을 찾아서 파일 작성자를 찾아서 인쇄하는 프로그램이 있습니다. 필자는 작성자 이름과 저자 이름 뒤에 저자 이름이 오는 파일의 저자를 인쇄하기 위해 아래 코드를 얻을 수있었습니다. 문제가있는 것은 저자 문자열이 전혀 존재하지 않을 때 Unknown을 인쇄하려고하는 것입니다. 즉, docstring의 일부에 Author이 포함되어 있지 않습니다.docstring에서 파이썬 파일의 저자를 찾으십시오.

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로 시작하는 어떤 라인이 없다면. 우리가 Unknown-name 기본 때문에

또는, 일찍 루프를 종료 할뿐만 아니라 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

관련 문제