-4
    import urllib2

    currency = 'EURO'
    req = urllib2.urlopen(' http://rate-exchange.appspot.com/currency?from=USD&to='+ currency +'') 
    result = req.read() 
    print p
    p = result["rate"]
    print int(p) 

这是我得到的print p 结果 = {“to”:“EURO”,“rate”:0.76810814999999999,“from”:“USD”}

但我有错误:

TypeError: string indices must be integers, not str
4

1 回答 1

10

.read()调用的结果不是字典,而是字符串:

>>> import urllib2
>>> currency = "EURO"
>>> req = urllib2.urlopen('http://rate-exchange.appspot.com/currency?from=USD&to='+ currency +'')
>>> result = req.read()
>>> result
'{"to": "EURO", "rate": 0.76810814999999999, "from": "USD"}'
>>> type(result)
<type 'str'>

看起来结果是一个 JSON 编码的字典,所以你可以使用类似的东西

>>> import json, urllib2
>>> currency = "EURO"
>>> url = "http://rate-exchange.appspot.com/currency?from=USD&to=" + currency
>>> response = urllib2.urlopen(url)
>>> result = json.load(response)
>>> result
{u'to': u'EURO', u'rate': 0.76810815, u'from': u'USD'}
>>> type(result)
<type 'dict'>
>>> result["rate"]
0.76810815
>>> type(result["rate"])
<type 'float'>

[请注意,尽管我认为有更好的方法来处理添加参数,例如fromand to另请注意,在这种情况下,将转换率转换为int.]

于 2013-03-13T15:40:36.170 回答