2016-11-11 179 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