运行此代码时为什么会出现AttributeError?

时间:2020-07-24 00:29:03

标签: python-3.x

from collections import Counter
import re
  

s = open( 'filename.txt', 'r')
words = re.findall('\w+', s.lower())
c = Counter(words)

for word, freq in c.most_common(10):
    print(word, ':' , freq)

执行代码时出现此错误,但我不知道为什么。我该怎么做才能纠正这个问题?

Traceback (most recent call last):
      File "./find_occurences_in_a_txt_file.py", line 9, in <module>
        words = re.findall( '\w+' , s.lower())
    AttributeError: '_io.TextIOWrapper' object has no attribute 'lower'

2 个答案:

答案 0 :(得分:3)

您需要将文件对象转换为字符串。您可以使用.read()进行此操作。另外,在处理文件时,应使用with而不是open,以便在处理完文件后自动将其关闭。 最后,您需要一个正则表达式的原始字符串(以r开头)

from collections import Counter
import re
  
words = []
with open( 'filename.txt', 'r') as s:
    words = re.findall(r'\w+', s.read().lower())
c = Counter(words)

for word, freq in c.most_common(10):
    print(word, ':' , freq)

答案 1 :(得分:1)

s不是字符串,而是文件,如EntagledLoops所说。

您可以执行s.read().lower()。如果这不是您想要的行为,请发表评论。