繁体   English   中英

定义一个名为articleStats()的函数,该函数采用名为fileName的字符串参数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM