Python str对象没有属性';关闭';
我正在分析文字的词频,完成后收到此错误消息:Python str对象没有属性';关闭';,python,text-analysis,Python,Text Analysis,我正在分析文字的词频,完成后收到此错误消息: 'str' object has no attribute 'close' 我以前使用过close()方法,所以我不知道该怎么办 代码如下: def main(): text=open("catinhat.txt").read() text=text.lower() for ch in '!"$%&()*+,-./:;<=>=?@[\\]^_{|}~': text=text.replace
'str' object has no attribute 'close'
我以前使用过close()
方法,所以我不知道该怎么办
代码如下:
def main():
text=open("catinhat.txt").read()
text=text.lower()
for ch in '!"$%&()*+,-./:;<=>=?@[\\]^_{|}~':
text=text.replace(ch,"")
words=text.split()
d={}
count=0
for w in words:
count+=1
d[w]=d.get(w,0)+1
d["#"]=count
print(d)
text.close()
main()
def main():
text=open(“catinhat.txt”).read()
text=text.lower()
为了钱!"$%&()*+,-./:;=?@[\\]^_{|}~':
text=text.replace(ch,“”)
words=text.split()
d={}
计数=0
对于w,大写:
计数+=1
d[w]=d.get(w,0)+1
d[“#”]=计数
印刷品(d)
text.close()
main()
这是因为您的变量
文本具有字符串类型(当您从文件中读取比赛时)
让我给你看一个确切的例子:
>>> t = open("test.txt").read()
#t contains now 'asdfasdfasdfEND' <- content of test.txt file
>>> type(t)
<class 'str'>
>>> t.close()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'close'
您没有保存对文件句柄的引用。您打开了文件,读取了文件内容,并保存了结果字符串。没有可关闭的文件句柄。避免这种情况的最佳方法是使用
上下文管理器:
def main():
with open("catinhat.txt") as f:
text=f.read()
...
这将在带有
块的结束后自动关闭文件,无需显式的f.close()
text
是一个str
,因为这是.read()
返回的内容。它没有关闭方法。文件对象会有关闭方法,但您没有为打开的文件指定名称,因此您无法再引用它来关闭它
我建议使用with
语句来管理文件:
with open("catinhat.txt") as f:
text = f.read()
...
无论块是否成功完成或引发异常,with
语句都将关闭文件。为什么要关闭字符串…-->text=open(“catinhat.txt”).read()
。可能需要with open(“catinhat.txt”)作为f:text=f.read();f.close()
@KevinGuan-如果你在使用上下文管理器,你不需要close()
,因为这是自动处理的。@TigerhawkT3啊,对了。我不知道为什么要添加f.close()
…所以我在结尾不需要close方法?@M.gnus:请参阅我的更新。您不能关闭字符串,但是在第二个示例中,您没有覆盖文件的open()
包装,因此您可以关闭它。
text=open("catinhat.txt").read()
with open("catinhat.txt") as f:
text = f.read()
...