-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でエンコードされたdictのように見えるので、次のようなものを使用できます

>>> 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'>

from[や などのパラメーターの追加を処理するより良い方法があると思いますが、URL の構成をそのままにしておいたことに注意してくださいto。また、状況によっては、コンバージョン率を に変換しても意味がないことに注意してくださいint。]

于 2013-03-13T15:40:36.170 に答える