我正在编写一个程序来读取邮政编码的文本文件,当输入正确的数字时,该文件应打印邮政编码的位置。但是,我在编写错误消息时遇到问题。我尝试了各种方法,无法获取打印错误信息,这就是我所拥有的:
Abbeville AL 36310
Abernant AL 35440
Acmar AL 35004
Adamsville AL 35005
Addison AL 35540
Adger AL 35006
Akron AL 35441
Alabaster AL 35007
一些示例邮政编码:
DayOfWeek
答案 0 :(得分:1)
我不确定enterFile的重要性。如果从异常中删除enterFile,则应该看到错误消息,因为它似乎没有定义。
答案 1 :(得分:0)
我相信您需要在此计划中分两个阶段:
您当前的"积极的"逻辑是
else:
for line in myFile:
words = line.split() # Get the next line from zipcodes.txt
if words[2] == ask: # If this ZIP code matches the input,
zipcode = words[0:2] # assign the line's three fields as a list.
# Variable zipcode now contains a single line's data, all three fields.
# You threw away the empty dictionary.
for value in zipcode: # Print all three fields of the one matching line.
print value,
需要逻辑(在我看来)
# Part 1: read in the ZIP code file
# For each line of the file:
# Split the line into location and ZIP_code
# zipcode[ZIP_code] = location
# Part 2: match a location to the user's given ZIP code
# Input the user's ZIP code, "ask"
# print zipcode[ask]
这个pseduo代码是否会让您转向解决方案?
答案 2 :(得分:0)
从一开始:
try:
myFile=open("zipcodes.txt")
except:
print "File can't be opened:", myFile # if open fail then myFile will be undefined.
exit()
zipcode = dict() # you creating dict, but you never add something into it.
line = myFile.readline() # this will read only first line of file, not each
ask = raw_input("Enter a zip code: ")
if ask not in line:
# it will print not found for any zipcode except zipcode in first line
print "Not Found."
else:
# because you already read 1 line of myFile
# "for line in " will go from second line to end of file
for line in myFile: # 1 line already readed. Continue reading from second
words = line.split()
if words[2] == ask: # If you don't have duplicate of first line this will never be True
zipcode = words[0:2]
# So here zipcode is an empty dict. Because even if "ask is in line"
# You never find it because you don't check line
# where the ask is (the first line of file).
for value in zipcode:
# print never executed becouse zipcode is empty
print value,