如何在“ascii”编解码器中编码字符“\xa0”

2024-10-02 12:36:00 发布

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

我正在尝试使用python使用Rest API获取数据,但收到以下错误:

   1132 
   1133         # Non-ASCII characters should have been eliminated earlier
-> 1134         self._output(request.encode('ascii'))
   1135 
   1136         if self._http_vsn == 11:

UnicodeEncodeError: 'ascii' codec can't encode character '\xa0' in position 86: ordinal not in range(128)

我的python代码是-

 df = pd.read_csv(r"data.csv", encoding='utf8', sep=",", 
                 engine="python")

def GoogPlac(auth_key,lat,lon):
    location = str(lat) + ',' + str(lon)
    MyUrl = ('https://places.ls.hereapi.com/places/v1/browse'
            '?apiKey=%s'
            '&in=%s'
            ';r=2000'
            '&cat=restaurant&pretty') % (auth_key,location)
    #grabbing the JSON result
    response = urllib.request.urlopen(MyUrl)
    jsonRaw = response.read()
    jsonData = json.loads(jsonRaw)
    return jsonData

# Function call
df['response'] = df.apply(lambda x: GoogPlac(auth_key,x['latitude'],x['longitude']), axis=1)

我希望避免错误并继续API获取


Tags: csvkeyinselfauthapidfread
1条回答
网友
1楼 · 发布于 2024-10-02 12:36:00

你说你想避免这个错误,但是你如何避免它很重要

你的标题说你想把东西编码成ASCII码,但是你想编码的东西不能用ASCII码编码。7位ASCII中没有A0字符。你问了一个不可能的问题

您可以在几个不同的事项中做出决定:

  • 使用lossy Encode()参数进行编码,该参数表示丢弃所有不符合ASCII的内容。这是危险的,可能不是很聪明。如果你不能信任你的数据,那么你为什么要使用你的数据
  • 对输出使用不同的编码。您似乎知道文本的编码方式,因为您可以获取文本并将其呈现为Unicode。(或者,您使用的是古老的Python 2,默认的系统编码可以理解该页面的编码,并且在.encode("ascii")之前有一个无声的.decode(DEFAULT_ENCODING)。这是目前为止最好的方案。只是不要使用ASCII。UTF-8是现在和未来
  • 特别是在你的.encode()前面用.replace()剪下A0。也很糟糕
  • 让你的页面作者同意它应该是ASCII码,并让他修复它。这是最好的

相关问题 更多 >

    热门问题