2017-03-24 11 views
0

私は、ファイルZipcodes.txtを受け取るクラスのためのPythonプログラムで、配列にそれを読み込んでいます。そうすることで、ユーザーは郵便番号を入力して都市と所在を知ることができます。Pythonクラスプロジェクト用の郵便番号検索プログラムを作成する

Zipcodes.txtファイルのようにフォーマットされた場合、CSVはセットアップ:

90401,SANTA MONICA,CA <br> 
90023,LOS ANGELES,CA<br> 

などを...

この私がこれまで持っているコード:

def main(): 
    # Trying this order of calling the functions 
    readFile() 
    readRecord() 
    promptUser() 
    printRecord() 

def readFile(): 
    # Tried following the example files that came with the Powerpoint 
    # Do I need this? What changes? 
    infile = open("zipcodes.txt","rb") 
    eof, zipRecord = readRecord(infile) 
    while not eof: 
     printRecord(infile) 
     eof, zipRecord = readRecord(zipRecord) 
    infile.close() 

def promptUser(): 
    zipQuery = input("Enter a zip code to find (Press Enter key alone to stop): ") 

def readRecord(infile):  
    zipSplit = infile.split(',') 
    zipCode = infile[0] 
    city = infile[1] 
    state = infile[2] 

def printRecord(): 
    # Print statement is like this for testing 
    print(city + state) 

main() 

結果は次のようになります。

Enter a zip code to find (Press Enter key alone to stop): 90401 
The city is SANTA MONICA and the state is CA. 

私はわずか8週間このクラスにしてきたと私はプログラミングの完全な初心者ですが、私は今のところ私の前に置くすべてを把握することができました。 私はこの車輪を回転させています。

+0

を参照してくださいテキスト内の\ nはCAの後にはあります? – Afaq

+0

質問は表示されません。 – excaza

+0

インデントが正しくない、あなたがそれらを整理して実行可能なプログラムを見ることができますか? – tdelaney

答えて

0

テスト、エラーハンドリングがなけれ:

import csv 
zip_info_dct = {} 
with open('zipcodes.txt"', 'rb') as csvfile: 
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') 
    for row in spamreader: 
     zip_code = row[0] 
     city = row[1] 
     state = row[2] 
     zip_info_dct [zip_code] = (city, state) 
zip_query = input("Enter a zip code to find (Press Enter key alone to stop): ") 
if zip_query in zip_info_dct : 
    info = zip_info_dct [zip_query] 
    print "The city is %s and the state is %s" % (info [0], info [1]) 

テキストファイルを読み込むためのニシキヘビの方法は次のとおりです。

f = open('zipcodes.txt', 'rt') 
for line in f : 
    print line 
f.close() 

https://docs.python.org/2/tutorial/inputoutput.html

関連する問題