|
编写一个统计词频的代码如下
def getText():
txt=open("hamlet.txt","r").read()
txt=txt.lower()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{丨}~':
txt=txt.replace(ch," ")
return txt
hamletTxt=getText()
words=hamletTxt.split()
counts={}
for word in words:
counts[word]=count.get(word,0)+1
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(10):
word,count=items[1]
print("{0:<10}{1:>5}".format(word,count))
系统报错为
Traceback (most recent call last):
File "D:/Python/练习/CalHamletV1.py", line 7, in <module>
hamletTxt=getText()
File "D:/Python/练习/CalHamletV1.py", line 2, in getText
txt=open("hamlet.txt","r").read()
FileNotFoundError: [Errno 2] No such file or directory: 'hamlet.txt'
但是我电脑上有这个文件,为什么会出现这样的问题,该如何解答呢?
|
|