大家好谢谢你们调查我的问题。我要做的是用python编写一个“结构化”程序,从文件中提取txt并将其解析为列表。然后在关闭文件之后,我需要引用这些列表中的用户输入(zipcode),然后根据输入的zipcode打印出城市和州。我的老师让我们通过几个函数来使用结构。我知道可能有很多更有效的方法来做到这一点,但我必须保持现有的结构。 编辑 这是我的代码(当前):
#-----------------------------------------------------------------------
# VARIABLE DEFINITIONS
eof = False
zipRecord = ""
zipFile = ""
zipCode = []
city = []
state = []
parsedList = []
#-----------------------------------------------------------------------
# CONSTANT DEFINITIONS
USERPROMPT = "\nEnter a zip code to find (Press Enter key alone to stop): "
#-----------------------------------------------------------------------
# FUNCTION DEFINITIONS
def startUp():
global zipFile
print "zipcode lookup program".upper()
zipFile = open("zipcodes.txt","r")
loadList()
def loadList():
while readRecord():
pass
processRecords()
def readRecord():
global eof, zipList, zipCode, city, state, parsedList
zipRecord = zipFile.readline()
if zipRecord == "":
eof = True
else:
parsedList = zipRecord.split(",")
zipCode.append(parsedList[0])
city.append(parsedList[1])
state.append(parsedList[2])
eof = False
return not eof
def processRecords():
userInput = raw_input(USERPROMPT)
if userInput:
print userInput
print zipCode
if userInput in zipCode:
index_ = zipcode.index(userInput)
print "The city is %s and the state is %s " % \
(city[index_], state[index_])
else:
print "\nThe zip code does not exist."
else:
print "Please enter a data"
def closeUp():
zipFile.close()
#-----------------------------------------------------------------------
# PROGRAM'S MAIN LOGIC
startUp()
closeUp()
raw_input("\nRun complete. Press the Enter key to exit.")
以下是zipcode txt文件的示例:
^{pr2}$我在这一点上肯定是卡住了,感谢您在这件事上的帮助。
编辑
谢谢大家的帮助。我真的很感激。:)
字符串不像列表那样有}附加到
append
方法。我认为您要做的是将字符串zipCode
、city
、和{parsedList
。这是您用来执行此操作的代码:或者,更简单地说:
^{pr2}$如果您收到另一条错误消息,请告诉我,我可以提供更多建议。在
Python的一个优点是它的交互性。如果将processRecords()从loadList()中取出,然后在程序的底部放入:
然后,在命令提示符下输入“python”。您将看到Python shell提示符,“>>>;”。在这里输入:
^{pr2}$这应该有助于调试。在
为什么要像这样填写列表zipcode,city,state,我的意思是在每个用户条目中我们都会从文件中得到下一行
我认为你应该:
关于您的问题:
^{pr2}$相关问题 更多 >
编程相关推荐