[英]Define a function called articleStats() that takes a string parameter named fileName
定義一個名為articleStats()的函數,該函數帶有一個名為fileName的字符串參數,代表文件名。 該文件包含用空格分隔的小寫單詞。 該函數返回所有文章的總數。 文章是以下單詞之一:a,the,an。
我知道這是一個非常簡單的問題,但我真的對自己做錯了什么感到困惑。 這是我到目前為止的內容,但我知道這是錯誤的
def articleStats(filename):
filename.split()
for word in filename:
if 'a' or 'the' or 'an' in word:
print(len(filename))
articleStats('an apple a day keeps the doctor away')
問題是if 'a' or 'the' or 'an' in word:
。 在Python中,字符串文字被評估為True
因此您的情況將被視為: if True or True or 'an' in word
將其更改為if 'a' in word or 'the' in word or 'an' in word
為了更好地了解正在發生的事情,請運行以下代碼以查看Python如何處理其他情況。
tests = [[], ['not empty list'], {}, {'not':'empty dict'}, 0, 1, '', 'not empty string']
for test in tests:
print test, bool(test)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.