访问网站时(Glosbe.com网站)通过json-API特殊字符不进行装饰

2024-04-19 06:17:17 发布

您现在位置:Python中文网/ 问答频道 /正文

访问此时Glosbe.com网站通过他们的API,下面的代码无法解码特殊字符或撇号。在

例如,它打印perché,而不是{}。当检查网站来源时,它说字符集是utf-8。有什么想法吗?在

# -*- coding: utf-8 -*-
import urllib.request
import json

url = ' http://glosbe.com/gapi/translate?from=fra&dest=eng&format=json&phrase=chat&pretty=true'


weburl = urllib.request.urlopen(url)
data = weburl.read().decode('utf-8') 

theJSON = json.loads(data)
print(theJSON)

Tags: 代码importcomapijsonurldata网站
1条回答
网友
1楼 · 发布于 2024-04-19 06:17:17

该网站似乎给你的数据与HTML实体。对HTML实体进行解码:

from html.parser import HTMLParser

def unescape_entities(value, parser=HTMLParser()):
    return parser.unescape(value)

def process(ob):
    if isinstance(ob, list):
        return [process(v) for v in ob]
    elif isinstance(ob, dict):
        return {k: process(v) for k, v in ob.items()}
    elif isinstance(ob, str):
        return unescape_entities(ob)
    return ob

theJSON = process(theJSON)

演示:

^{pr2}$

相关问题 更多 >