【问题标题】:UnicodeEncodeError with character u'\u2013带有字符 u'\u2013 的 UnicodeEncodeError
【发布时间】:2019-04-29 01:48:58
【问题描述】:

我收到以下带有破折号“-”的错误

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

我已尝试使用以下内容:skills.encode('utf-8') 但我仍然收到错误消息。下面是我尝试写入 csv 的代码。

 writer.writerow([name.encode('utf-8'),
                 heading.encode('utf-8'),
                 location.encode('utf-8'),
                 education.encode('utf-8'),
                 summary,
                 currentRole,
                 allRoles,
                 companiesFollowed,
                 groups,
                 skills.encode('utf-8')])

【问题讨论】:

  • 只有你能说出那个角色应该是什么。
  • 字符是破折号
  • 啊,不仅仅是普通的- 破折号,而是一个n-dash fileformat.info/info/unicode/char/2013/index.htm。是的,你不能用 ASCII 来表示它。你想在那里做什么?
  • 如果可能的话,只是一个普通的破折号。我不知道破折号和破折号之间的区别。
  • 如果你使用 Python3,你会得到什么(你可以跳过encodes)。如果你不这样做,你将不得不学习比你现在所知道的更多的关于 Unicode 以及 Unicode 代码点的含义的知识。我不知道有任何函数可以知道您希望 n-dash 成为连字符。您可以使用string.maketransstr.translate 进行自己的字符串替换,仅此而已。

标签: python ascii


【解决方案1】:

您可以在errors 关键字下为str.encode 指定多个设置之一。可以在in the docs 找到更多信息,但我建议您使用'replace' 错误处理程序。

writer.writerow([name.encode('utf-8', errors='replace'),
    heading.encode('utf-8', errors='replace'),
    location.encode('utf-8', errors='replace'),
    education.encode('utf-8', errors='replace'),
    summary,
    currentRole,
    allRoles,
    companiesFollowed,
    groups,
    skills.encode('utf-8', errors='replace')])

这最终会生成一个带有?bytes 对象来代替每个不可编码的代码点。

【讨论】:

  • 感谢您的回复@Adam。不幸的是,这不起作用我收到了这个错误:skills.encode('utf-8', errors='replace')]) UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 38: ordinal not in范围(128)
  • @dcraven 我无法重现该结果。你运行的是什么版本的 Python?
猜你喜欢
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
  • 2011-07-20
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
相关资源
最近更新 更多