从文本文件

时间:2017-03-12 08:53:35

标签: python python-2.7 dictionary

所以,我有一个文本文件,如下所示:

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

我想要做的就是通读并将每种货币放入自己的字典中。  AUD {AUD_CHF: 0.77324, AUD_EUR :0.72657 AUD_GBP :0.61557 AUD_JPY :6.88, AUD_USD :0.76835} 然后是CHF,USD等。完成后会有18个词典。我已经设法用下面的代码(在另一个问题上提供一些帮助)这样做但是它很长并且不是我理解的非常pythonic。看起来像这样

USD = {}
AUD = {}
CHF = {}
with open('rates.txt', 'r') as f:
    for line in f:
        split_line = line.split()
        if line.startswith('USD'):
            USD[split_line[0]] = split_line[1]
        elif line.startswith('AUD'):
            AUD[split_line[0]] = split_line[1]
        elif line.startswith('CHF'):
            CHF[split_line[0]] = split_line[1]

我的意思是,它有效,但我不能想象没有更好的方法。我和一位朋友交谈,他提出了一个解决方案,它使用了vars(),local(),从我读到的内容来看,这不是一件好事,我无法按照我想要的方式工作。我在考虑某种循环,但我无法做任何事情。如果有人有任何想法让我尝试,我将不胜感激。即使它只是一个骨架,所以我可以去尝试让它发挥作用。

感谢您的时间,道歉这有点长。

1 个答案:

答案 0 :(得分:1)

字典词典和默认词典怎么样:

from collections import defaultdict
currencies = defaultdict(dict)

with open('rates.txt', 'r') as f:
    for line in f:
       if line:
          currency, rate = line.split()
          currencies[currency[:3]][currency] = rate

导致:

In [39]: currencies['AUD']
Out[39]:
{'AUD_CHF': '0.77324',
 'AUD_EUR': '0.72657',
 'AUD_GBP': '0.61557',
 'AUD_JPY': '86.88',
 'AUD_USD': '0.76835'}

In [40]: currencies['CHF']
Out[40]: {'CHF_EUR': '0.939858457', 'CHF_GBP': '0.795924865'}

In [41]: currencies['CAD']
Out[41]: {'CAD_CHF': '0.76915', 'CAD_EUR': '0.722459831', 'CAD_GBP': '0.612726326'}

编辑。

如果你的线条不符合空格分隔,你可以试试try / except块等等:

from collections import defaultdict
currencies = defaultdict(dict)

with open('rates.txt', 'r') as f:
    for line in f:
       if line:
          try:
              currency, rate = line.split()
          except ValueError:
               # good practice to log here, if you were to have logging.
               continue #skip to next line
          currencies[currency[:3]][currency] = rate