从python 3中的文本文件中提取数据

时间:2017-06-17 07:25:03

标签: python

我很难通过文本文件将最后的数据提取到我的程序中。我是Python的新手,如果答案非常简单,请原谅我。

我在文本文件中设置了这个数据序列,并且我已经提取美元作为我的卖出货币GBP作为我的买入货币,并且已经提取0.50443作为我的汇率。但我不知道如何提取成本作为我的交易成本和0.0001作为该变量的相关值。

{"USD_GBP_COST": "0.50443,0.0001", "USD_USD_COST": "1.00000,0.0000", "USD_EUR_COST": "0.73951,0.01211"}

以下是我的其他部分的代码:

currency_rates = json.loads(page)

 splited_rates = re.compile("([A-Z]{3})_([A-Z]{3})")#split the string which is read from the url,it should be any 3 uppercase characters sperated by a _ 

for key in currency_rates:
    matches=splited_rates.match(key)
    log_con_rate = -math.log(float(currency_rates[key]))
    selling_currency = matches.group(1).encode('ascii','ignore')
    buying_currency = matches.group(2).encode('ascii','ignore')

1 个答案:

答案 0 :(得分:0)

问题在于:

float(currency_rates[key])

,它给出了错误ValueError: could not convert string to float: '0.50443,0.0001'。我认为这个消息非常明显。它告诉您在尝试将字符串转换为float之前需要将字符串分成两个数字:

con_rate_s, transaction_cost_s = currency_rates[key].split(",")
log_con_rate = -math.log(float(con_rate_s))
transaction_cost = float(transaction_cost_s)