我想将文本文件中的特定行添加到字典中。我们的想法是将所有以AUD开头的行添加到带有密钥的AUD字典中。然后CAD和列表。
我尝试过搜索和添加一些内容的一些变体。我对回答感到好奇,因为我是错误以及他们在学习时的意思。我正处于Python的开头,如果我的尝试让你的眼睛流血,我会道歉。非常感谢你的时间。
这是.txt文件pastebin
的格式这会将所有内容添加到字典中,我只想要AUD
with open('rates.txt') as f:
for line in f:
if line.startswith('AUD') == True: # returns true on pairs I want to add
AUD = dict(x.rstrip().split(None, 1) for x in f) #adds everything
else:
pass
print AUD
接下来我尝试了这个返回" ValueError:需要多于1个值才能解压"
AUD = {}
with open("rates.txt") as f:
for line in f:
if line.startswith('AUD'):
(key, val) = line.split(' ') #The space inbetween the '' causes the error?
AUD[int(key)] = val
print AUD
最后我正在处理这个问题,它返回了' KeyError:' AUD_CHF'
AUD = {}
with open("rates.txt") as f:
for line in f:
if 'AUD_' in line:
key, value = line.strip().split('')
AUD [key].append(value)
print AUD
答案 0 :(得分:0)
AUD = {}
with open("rates.txt") as f:
for line in f:
if 'AUD_' in line:
key , value = line.lstrip('AUD_').split(' ')
AUD[key] = value
print AUD
这应该可以解决问题。我改变了你的字符串"解析器"直接通过删除&_ 39; AUD _'直接产生转换的货币。在前面。您可以通过将前3个字母作为字典名称来选择要编写的字典来进一步改进您的脚本。
答案 1 :(得分:0)
你在第一个例子中很接近你。
您不需要== True
语句中的if
,因为str.startswith()
会返回由if
评估的布尔值。与此同时,我纠正了一些缩进。
AUD = {}
with open('rates.txt', 'r') as f:
for line in f:
if line.startswith('AUD'):
split_line = line.split()
AUD[split_line[0]] = split_line[1]
else:
pass
print AUD
答案 2 :(得分:0)
你回答的距离不远。 务必清理数据。 文件通常以空行结束,这可能导致您的拆分失败。
data = """
AUD_CHF 0.77324
AUD_EUR 0.72657
AUD_GBP 0.61557
AUD_JPY 86.88
AUD_USD 0.76835
CAD_EUR 0.722459831
CAD_GBP 0.612726326
CAD_CHF 0.76915
CHF_EUR 0.939858457
CHF_GBP 0.795924865
"""
#remove empty lines
lines = [l for l in (line.strip() for line in data.split('\n')) if l ]
AUD = {}
for line in lines:
#the two folowing lines could be in a function
curencies, rate = line.split()
cur1, cur2 = curencies.split('_')
#debug
#print cur1, '->', cur2, ' ', value
if cur1 == 'AUD':
AUD[cur2] = rate
for currency, rate in AUD.items():
print '1 AUD =', rate, currency
在您的核心中只需用file.readlines()替换data.split(' \ n')。