【问题标题】:How to resolve UnicodeEncodeError storing data in json format如何解决 UnicodeEncodeError 以 json 格式存储数据
【发布时间】:2017-11-09 11:56:44
【问题描述】:

我从网站上抓取了数据,但对于某些项目,它显示以下错误:

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

我什至在文档顶部放了“# -- coding: utf-8 --”,但它不起作用。请帮忙。

【问题讨论】:

  • 这不是# -- coding: utf-8 -- 的用途。显示您的代码。
  • @michael 。您需要在打印数据或将其写入文件时对数据进行编码,您所做的是一种指定 Python 文件编码的方式
  • 我们是否应该猜测您的代码此时正在做什么以及您的数据是什么样的?

标签: python python-unicode


【解决方案1】:

要么始终考虑unicode 内容,要么完全删除unicode 内容。发生错误是因为您(或您正在使用的某些库方法)试图将 utf-8 内容转换为 ascii 而不忽略错误。

# Ignore unicode content
content_string = content_string.encode('ascii', 'ignore')

# Or make sure you handle unicode content as such. It would have been
# easier if you're using Python3x.

# -- coding: utf-8 -- 的目的是允许将 Unicode 内容显式添加到 python 代码文件中,而不是设置默认编码。

# -- coding: utf-8 --
book_name = 'Les Misérables'

【讨论】:

    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 2023-03-29
    • 2014-06-15
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多