2016-11-11 181 views
0

我正在编写一个程序来读取应输入正确数字时应打印邮政编码位置的邮政编码文本文件。但是,我在编写错误消息时遇到了问题。我已经尝试了各种方法并不能得到错误信息打印,这里是我有:搜索文件输入Python

try: 
    myFile=open("zipcodes.txt") #Tries to open file user entered 
except: 
    print "File can't be opened:", myFile #If input is invalid filename, print error 
    exit() 

zipcode = dict() #List to store individual sentences 
line = myFile.readline() #Read each line of entered file 

ask = raw_input("Enter a zip code: ") 

if ask not in line: 
    print "Not Found." 
else: 
    for line in myFile: 
     words = line.split() 
     if words[2] == ask: 
      zipcode = words[0:2] 
for value in zipcode: 
    print value, 

一些样品邮政编码:

Abbeville   AL 36310 
Abernant   AL 35440 
Acmar    AL 35004 
Adamsville  AL 35005 
Addison   AL 35540 
Adger    AL 35006 
Akron    AL 35441 
Alabaster   AL 35007 
+0

你可以添加 “zipcodes.txt” 的部分质疑?前三条线就足够了。 – Arnial

+0

代码下面有一些样本。 – AndrewSwanson94

+0

'readline'方法只读取1行。我需要'读''的东西。 – Arnial

回答

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, 
+0

这解释了为什么输入正确时不打印任何内容。我不确定为什么它不打印除“36310”之外的任何输入的“未找到”。我运行这个代码,并添加问题zipcode.txt,它总是打印“找不到”其他邮编。 – Arnial

+0

我自己想出来了,关闭了。 – AndrewSwanson94

1

我不知道的enterFile的意义。如果您从异常中删除了enterFile,您应该会看到该错误消息,因为它似乎没有被定义。

+0

这是我忘了从旧代码中拿出来的东西,我会修复它 – AndrewSwanson94

+0

问题是当我改变的时候,如果问不在线:如果问问问题:代码工作,但我没有得到任何错误消息。 – AndrewSwanson94

0

我相信,你需要在这个程序分为两个阶段:

  1. 阅读zipcodes.txt,建立自己的目录。
  2. 询问用户邮政编码;打印相应的位置。

您当前的 “积极” 的逻辑

所需逻辑(在我看来)

# 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码让你朝着一个解决方案移动?

+0

不是。主要的问题是,如果问不在:声明不能正常工作,我不知道为什么。 – AndrewSwanson94