为Python类项目制作邮政编码搜索程序

时间:2017-03-24 18:41:13

标签: python arrays csv

我一直在研究一个带有文件的类的python程序,Zipcodes.txt将其读入数组。这样做可以让用户输入他们的邮政编码并获得它所属的城市和州。

如果格式化为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周,而且我是一个完整的编程新手,但我已经能够弄清楚到目前为止摆在我面前的一切。 我在这个上旋转。

1 个答案:

答案 0 :(得分: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])

读取文本文件的pythonic方法是:

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

请参阅https://docs.python.org/2/tutorial/inputoutput.html