gpt4 book ai didi

python - Unicode解码错误: 'utf8' codec can't decode byte - Euro Symbol

转载 作者:行者123 更新时间:2023-11-28 21:58:33 25 4
gpt4 key购买 nike

我建立了到 Google Finance API 的连接,它为我提供了股票报价。一切正常,直到我转到欧洲的类(class)。这些包含 € 符号,我收到以下错误:

Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\getQuotes.py", line 32, in <module>
quote = c.get("SAP","FRA")
File "C:\Users\Administrator\Desktop\getQuotes.py", line 21, in get
obj = json.loads(content[3:])
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 381, in raw_decode
obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 0: invalid start byte

以下是我使用的代码。我猜是在 json 尝试处理字符串时出现错误,但他无法解析欧元符号:

import urllib2
import json
import time

class GoogleFinanceAPI:
def __init__(self):
self.prefix = "http://finance.google.com/finance/info?client=ig&q="

def get(self,symbol,exchange):
url = self.prefix+"%s:%s"%(exchange,symbol)
u = urllib2.urlopen(url)
content = u.read()

obj = json.loads(content[3:])
return obj[0]


if __name__ == "__main__":
c = GoogleFinanceAPI()

while 1:
quote = c.get("MSFT","NASDAQ")
print quote
time.sleep(30)

这就是 Google 财经如何为我提供包含欧元符号的 SAP 股票的输出:

// [ { "id": "8424920" ,"t" : "SAP" ,"e" : "FRA" ,"l" : "56.51" ,"l_cur" : "€56.51" ,"s": "0" ,"ltt":"8:00PM GMT+2" ,"lt" : "Aug 7, 8:00PM GMT+2" ,"c" : "-0.47" ,"cp" : "-0.82" ,"ccol" : "chr" } ]

json.loads(unicode(opener.open(...), "ISO-8859-15"))

如果有人有想法,我会很高兴。

最佳答案

您正在获取的文档似乎是使用 Windows 代码页 1252 编码的,其中欧元符号字符编码为 \x80。这是 UTF-8 中的无效字节和所有 ISO-8859 变体中的非打印控制字符。尝试:

obj = json.loads(content[3:], 'cp1252')

关于python - Unicode解码错误: 'utf8' codec can't decode byte - Euro Symbol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18115997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com