[英]Python - Dictionary, Pickle
I'm taking an intro to Python class and I can't get my program to work.我正在介绍 Python class,但我的程序无法运行。 Here is the project explanation:以下是项目说明:
The "UN.txt" file basically contains a listing of country, continent, population, area (Example: Albania,Europe,3.0,11100) “UN.txt”文件基本上包含国家、大陆、人口、地区的列表(例如:阿尔巴尼亚、欧洲、3.0、11100)
Here is the program I created (using pythonanywhere.com):这是我创建的程序(使用 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()
It creates the Nationdict.dat
file but it just contains these 5 characters €}”.
它会创建Nationdict.dat
文件,但它只包含这 5 个字符€}”.
Can you please tell me what am I doing wrong?你能告诉我我做错了什么吗? I've been over this so many times and looked through tons of articles, help sites, etc, and can't figure out what I'm missing.我已经经历了很多次,浏览了大量的文章、帮助网站等,但无法弄清楚我错过了什么。
Appreciate it!欣赏它!
Jes杰斯
You are not doing anything wrong, pickle generates a file that is not human readable.您没有做错任何事情,pickle 会生成一个人类不可读的文件。 To check if it works run another program要检查它是否有效,请运行另一个程序
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.