如何在 'ascii' 编解码器中编码字符 '\xa0'
how to encode character '\xa0' in 'ascii' codec
我正在尝试使用 Here's Rest API 使用 python 获取数据,但我收到以下错误,
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获取
你说你想避免这个错误,但你如何避免它很重要。
您的标题说您想将某些内容编码为 ASCII,但您要编码的内容无法用 ASCII 编码。 7 位 ASCII 中没有 A0 字符。你问了不可能的问题。
您可以在几个不同的事情中做出决定:
- 使用有损 encode() 参数进行编码,该参数表示丢弃所有不适合 ASCII 的内容。这是危险的,而且可能不是很聪明。如果您不能信任您的数据,那么您为什么要使用您的数据?
- 对输出使用不同的编码。您似乎知道文本的编码方式,因为您可以获取它并将其呈现为 Unicode。 (或者,您使用的是古代 Python 2,并且默认系统编码理解该页面的编码,并且
.encode("ascii")
之前有一个无声的 .decode(DEFAULT_ENCODING)
。这是迄今为止最好的方案。只是不要使用 ASCII。UTF-8 是现在和未来!
- 在你的
.encode()
之前用.replace()
专门剪掉A0。也很糟糕。
- 让您的页面作者同意它应该是 ASCII 并让他修复它。这是最好的。
我正在尝试使用 Here's Rest API 使用 python 获取数据,但我收到以下错误,
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获取
你说你想避免这个错误,但你如何避免它很重要。
您的标题说您想将某些内容编码为 ASCII,但您要编码的内容无法用 ASCII 编码。 7 位 ASCII 中没有 A0 字符。你问了不可能的问题。
您可以在几个不同的事情中做出决定:
- 使用有损 encode() 参数进行编码,该参数表示丢弃所有不适合 ASCII 的内容。这是危险的,而且可能不是很聪明。如果您不能信任您的数据,那么您为什么要使用您的数据?
- 对输出使用不同的编码。您似乎知道文本的编码方式,因为您可以获取它并将其呈现为 Unicode。 (或者,您使用的是古代 Python 2,并且默认系统编码理解该页面的编码,并且
.encode("ascii")
之前有一个无声的.decode(DEFAULT_ENCODING)
。这是迄今为止最好的方案。只是不要使用 ASCII。UTF-8 是现在和未来! - 在你的
.encode()
之前用.replace()
专门剪掉A0。也很糟糕。 - 让您的页面作者同意它应该是 ASCII 并让他修复它。这是最好的。