【问题标题】:'ascii' encoding error in pythonpython中的'ascii'编码错误
【发布时间】:2016-04-12 15:33:22
【问题描述】:

我正在编写代码以从 NPR API 获取信息,但我一直遇到编码错误。我尝试了.encode('utf-8'),但我似乎找不到放置它的位置,而且我不断收到错误消息。

这是我的代码:

import json
import requests

def pretty(obj):
    return json.dumps(obj, sort_keys = True)

def NPR(
    baseurl = 'http://api.npr.org/query?', 
    apiKey = 'MDIzNjY4Mzk5MDE0NjAzMTcwMzNjNGZjOA000',
    id = '1126',
    output = 'json',
    numResults = '50',
    feilds = 'text',
    dateType = 'story',
    cache_fname="cached_data.txt",
    extra_params={}):

    d = {}
    d['id'] = id
    d['feilds'] = feilds
    d['dateType'] = dateType
    d['output'] = output
    d['numResults'] = numResults
    d['apiKey'] = apiKey
    resp = requests.get(baseurl, params = d)
    print resp.url
    print "caching data"
    f = open(cache_fname, 'w')
    f.write(resp.text)
    f.close()
    return resp.text

NPR(cache_fname="NPR_Africa.txt")

我得到的错误是:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2014' in position 10636: ordinal not in range(128)

上线f.write(resp.text)

【问题讨论】:

标签: python api unicode encoding ascii


【解决方案1】:

以 utf-8 编码的文本文件形式打开文件:

f = open(cache_fname, 'wt', encoding='utf-8')

但这仅适用于 Python 3。

Python 2:

如果 resp.text 是 unicode 字符串,则 resp.text.encode('utf-8') 应该可以工作。

【讨论】:

  • 如果作者明确使用 python 3,这比在重复参考中找到的答案更好。 +1(也就是说,此代码是 python2.x,如无括号打印语句所示。)
猜你喜欢
  • 2023-03-04
  • 2014-08-14
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 2015-01-28
  • 2015-02-03
  • 2019-09-01
  • 1970-01-01
相关资源
最近更新 更多