我在空闲时间使用我在亚马逊上购买的一本书来学习Python,在每一章的最后都有一些练习可以使用你刚才学到的东西。 其中一个练习是关于编写一个程序,给定一个目录,创建一个包含以下内容的字典:
这是我提出的:
import re
import os
directory = input("what's the directory?")
for file in os.listdir(directory):
for file in directory:
with open(file) as doc:
r_doc = doc.read()
parole = re.split(r"\W+",r_doc.lower()) #create a list of all the words in the text using as a division non-alphanumeric elements
parola = list(set(parole)) #get a list that contains each word only once
for i in parola:
contenenti = []
if i in r_doc:
contenenti.append(r_doc)
kseq = i
vseq = contenenti
dizionario = dict(zip(kseq,vseq))
我一直收到错误:“没有这样的文件或目录” 目录或代码完全错误是否有问题? 提前感谢任何回答的人
答案 0 :(得分:0)
directory
是一个字符串。您将file
从目录中的文件重新定义为字符串中的字符
directory = input("what's the directory?") # a string
for file in os.listdir(directory): # some files
for file in directory: # file redefined as character iterator in string
with open(file) as doc: # using the character from directory here
# which does not exist on your harddrive
解决方案:删除for file in directory: