[英]Python - Dictionary, Pickle
我正在介紹 Python class,但我的程序無法運行。 以下是項目說明:
“UN.txt”文件基本上包含國家、大陸、人口、地區的列表(例如:阿爾巴尼亞、歐洲、3.0、11100)
這是我創建的程序(使用 pythonanywhere.com):
import pickle
def main():
createDictionaryofNations()
def createDictionaryofNations():
nationdict = {}
for line in open("UN.txt", 'r'):
data = line.split(',')
country = Nation()
country.setName(data[0])
country.setContinent(data[1])
country.setPopulation (float(data[2]))
country.setArea (float(data[3].rstrip()))
nationdict[country.getName()] = country
pickle.dump(nationdict, open("nationdict.dat", 'wb'))
return nationdict
class Nation:
def __init__(self):
self._name = ""
self._continent = ""
self._population = 0.0
self._area = 0
def setName(self, name):
self._name = name
def getName(self):
return self._name
def setContinent(self, continent):
self._continent = continent
def getContinent(self):
return self._continent
def setPopulation(self, population):
self._population = population
def getPopulation(self):
return self._population
def setArea(self,area):
self._area = area
def getArea(self):
return self._area
def popDensity(self):
return self._population / self._area
main()
它會創建Nationdict.dat
文件,但它只包含這 5 個字符€}”.
你能告訴我我做錯了什么嗎? 我已經經歷了很多次,瀏覽了大量的文章、幫助網站等,但無法弄清楚我錯過了什么。
欣賞它!
傑斯
您沒有做錯任何事情,pickle 會生成一個人類不可讀的文件。 要檢查它是否有效,請運行另一個程序
import pickle
import so # so.py is my name of the file with your code from the question
print(pickle.load(open( "nationdict.dat", "rb")))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.