【问题标题】:how to encode character '\xa0' in 'ascii' codec如何在“ascii”编解码器中编码字符“\xa0”
【发布时间】:2020-10-05 01:32:58
【问题描述】:

我正在尝试使用 Python 使用 Here's 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 提取

【问题讨论】:

  • 你必须通过ignore。前 - request.encode('ascii', 'ignore')
  • 究竟哪一步应该消除非ASCII字符?
  • 我不确定应该在代码的哪个位置添加编码语句。

标签: python dataframe ascii rest


【解决方案1】:

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

您的标题说您想将某些内容编码为 ASCII,但您要编码的内容无法以 ASCII 编码。 7 位 ASCII 中没有 A0 字符。你问的是不可能的事。

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

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

【讨论】:

  • 非常感谢:)
猜你喜欢
  • 2017-05-30
  • 2016-02-12
  • 2015-10-21
  • 2010-12-11
  • 2012-07-02
  • 2010-12-11
  • 1970-01-01
相关资源
最近更新 更多