撰寫 docstring
你決定要打造全世界最強的開源自然語言處理 Python 套件。它將徹底改變處理非結構化文字的方式,就像 numpy 之於陣列、pandas 之於表格資料、scikit-learn 之於機器學習一樣。
你要寫的第一個函式是 count_letter()。它接收一個字串與單一字母,回傳該字母在字串中出現的次數。你希望這個開源套件的使用者能輕鬆理解這個函式如何運作,因此需要為它撰寫 docstring。請依照以下步驟,為此函式建立一個 Google 風格的 docstring。
本練習屬於課程
Python 函式寫作
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Add a docstring to count_letter()
def count_letter(content, letter):
____
if (not isinstance(letter, str)) or len(letter) != 1:
raise ValueError('`letter` must be a single character string.')
return len([char for char in content if char == letter])