def get_text():
with open("hamlet.txt","r",encoding='utf-8') as txt:
#把所有字母转换成小写字母
txt = txt.lower()
#剔除文本的特殊符号
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(ch," ")
return txt
报错了:AttributeError: ‘_io.TextIOWrapper’ object has no attribute ‘lower’
原因
这个错误提示通常会出现在尝试对一个 _io.TextIOWrapper 对象调用 lower() 方法时。lower() 方法是字符串对象的方法,用于将字符串中的所有字符转换为小写字母。
要解决这个错误,需要在调用 lower() 方法之前将文件内容转换为字符串。可以使用 str() 函数或文件对象的 readlines() 方法读取文件中的所有行并将它们连接成一个字符串,然后再进行大小写转换。
修正后代码
def get_text():
with open("hamlet.txt","r",encoding='utf-8') as txt:
#把所有字母转换成小写字母
txt = ''.join(txt.readlines())
#print("txt:\n",txt)
txt = txt.lower()
#剔除文本的特殊符号
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(ch," ")
return txt