新人学Python,编写小函数时遇到的问题求助
目的是读一个文件,找出里面出现 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’
新人学Python,编写小函数时遇到的问题求助
lower 是用于单个字符串的,你的 contents 调用了 split 函数过后成了 list,这就是它这样提示的原因。
我无法理解你的问题
或许你可以先 lower 再 split
直接正则取数量,count 获取的时候会把包含 the 的都算进去,不止是 the 比如 these 也会计算到 the 里的
不大懂 python,但是朋友,你的 if 去哪了? else 没有 if
首先你是不是忘记了 words 是列表了? 你对列表调用.lower()能不报错?
你应该在 words=contents.split()之前添加一句:contents=contents.lower()
try:…except:…else:…是 Python 语法,else 可以跟在 except 后,不一定非要是 if.
列表没有 lower()方法哦
lower()是用在字符串上的吧,你把内容已经 split()成了 list,除非你用 for 遍历,然后 lower(),不然肯定报错?
建议不要用 else 在这里,因为 except 之内的代码块没有执行的话,会直接执行接下来的内容,这个 else 本身就是多此一举。
try–except 是针对可能的报错引发程序崩溃而存在的。
还有,你的函数最好封包一下吧,不然怎么直接调用?
P.s.Python 很久没用了,如果有说错的或者不周全的,见谅哈…
感谢楼上们的指点,对列表确实不能使用 lower(),在成为列表前前加上 contents=contents.lower()就能解决了。另外,正则计算的使用还没学到,不过我会记下这个提示的,谢谢大家!
如果看系统库的话,python 官方还是很推荐用 try-except-else 的写法的,除非你在 except 中直接就 return 了,否则后面的代码在前面 open 出错了之后执行就会找不到 contents 这个变量

