我正在尝试将包含国家名称及其人均收入的文本文件存储到字典中,然后输出字典。
到目前为止,我所拥有的代码将文件存储在字典中并成功输出,除非我不知道如何在不从值中删除美元符号的情况下做到这一点。
到目前为止,这是我的代码:
def extractData(infile) :
record = {}
line = infile.readline()
if line != "" :
fields = line.split('$')
record["country"] = fields[0]
record["percap"] = int(fields[1].replace(',', ""))
return record
infile = open("percapita.txt", "r")
record = extractData(infile)
while len(record) > 0:
print("%-20s %10d" % (record["country"], record["percap"]))
record = extractData(infile)
我该如何解决?
答案 0 :(得分:1)
您似乎正在使用$分割行。这意味着它不再是您产品线的一部分。 我建议改用空白标识符之一(以适合文本文件的标识符为准)。
def extractData(infile) :
record = {}
line = infile.readline()
if line != "" :
fields = line.split(' ') # or '\t'
record["country"] = fields[0]
record["percap"] = int(fields[1].replace(',', ""))
return record
infile = open("percapita.txt", "r")
record = extractData(infile)
while len(record) > 0:
print("%-20s %10d" % (record["country"], record["percap"]))
record = extractData(infile)
答案 1 :(得分:0)
您并未在所有情况下都将键与值相关联,在每次迭代中都会删除字典,因此,当您要访问一个值时,将只有最后一个
我推荐这个
def extractData(infile) :
record = {}
while True:
line = infile.readline()
if line == "" :
break
fields = line.split('$')
record[fields[0]] = int(fields[1].replace(',', ""))
return record
infile = open("percapita.txt", "r")
record = extractData(infile)
for k in record.keys():
print(k , " $" , record[k])
答案 2 :(得分:0)
除了@Stephopolis的答案外,我认为您并未出于目的使用字典。您的键值应为国家/地区名称。例如,您应该添加以下值:
record["IsleofMan"] = "$83100"
,当您想获取某个国家的人均价值时,只需从词典中查询它即可。
print(record["IsleofMan"])
将给出
的输出$83100
要获取用户输入,您可以使用:
country_query = input()
所以当我们把它们放在一起时
def extractData(infile) :
record = {}
line = infile.readline()
if line != "" :
fields = line.split(' ') # or '\t'
record[fields[0]] = fields[1]
return record
infile = open("percapita.txt", "r")
record = extractData(infile)
country_query = input()
print(record["IsleofMan"])
进一步阅读 Dictionaries Input