目的是读一个文件,找出里面出现 the 的次数,为了把所有的大写也算进去,加入了 lower (),但是发现 lower ()放进去就报错,删掉就没问题。大家帮我看看怎么改好
def count_words(filename):
try:
with open(filename) as obj:
contents=obj.read()
except FileNotFoundError:
msg="sorry, the file "+filename+" does not exist."
print(msg)
else:
words=contents.split()
numbers=words.lower().count('the')
print("There are "+str(numbers)+" 'the' appears in "+ filename+".")
filename='alice.txt'
count_words(filename)
报的错误如下:
Traceback (most recent call last):
File "exercise1010.py", line 14, in <module>
count_words(filename)
File "exercise1010.py", line 10, in count_words
numbers=words.lower().count('the')
AttributeError: 'list' object has no attribute 'lower'
def count_words(filename):
try:
with open(filename) as obj:
contents=obj.read()
except FileNotFoundError:
msg="sorry, the file "+filename+" does not exist."
print(msg)
else:
words=contents.split()
numbers=words.lower().count('the')
print("There are "+str(numbers)+" 'the' appears in "+ filename+".")
filename='alice.txt'
count_words(filename)
报的错误如下:
Traceback (most recent call last):
File "exercise1010.py", line 14, in <module>
count_words(filename)
File "exercise1010.py", line 10, in count_words
numbers=words.lower().count('the')
AttributeError: 'list' object has no attribute 'lower'