【问题标题】:ASCII codec can't encode character u'\u2013'ASCII 编解码器无法编码字符 u'\u2013'
【发布时间】:2016-10-14 09:07:06
【问题描述】:

我在 Q_GIS 中有一些 Python 代码可以打开对象。我遇到的问题是目录中有一个无法编码的字符(类似下划线的字符)。错误是:

Traceback(最近一次调用最后一次):文件“”,第 1 行,in UnicodeEncodeError: 'ascii' 编解码器无法对字符 u'\u2013' 进行编码 位置 10:序数不在范围内(128)

我的小代码是:

from os import startfile; 
proj = QgsProject.instance(); 
UriFile = str(proj.fileName()); 
img = '[% "pad" %]'; 
Path = str(os.path.dirname(UriFile)); 
startfile(Path+img)

由于我的编程能力不强,所以请你帮我在这个小代码中添加一些代码来解决这个问题。

【问题讨论】:

    标签: python unicode


    【解决方案1】:

    我假设:

    • 您使用的是 Python2 版本
    • QgsProject.instance().fileName() 是一个包含 EN-DASH (Unicode char U+2013: –) 的 unicode 字符串,它看起来像一个普通的破折号 (Unicode char U+2D: -),但不存在于 ASCII 中,也不存在于任何常见的 8 位字符集中。

    那么这个错误就正常了:在Python2中,一个unicode字符串到一个普通的8bits字符串的转换使用了ASCII字符集。

    解决方法:
    您可以使用显式编码要求为未映射的字符使用 replace 字符:

    UriFile = proj.fileName().encode('ascii', 'replace')
    

    至少你会看到有问题的字符出现在哪里。

    解决方案:

    您应该使用完整的 unicode 处理(并使用 Python3)或确保处理的所有字符串都可以在您当前的字符集(通常是 latin1)中表示

    或者,如果它在您的用例中有意义,您可以尝试使用 UTF8 编码,它可以成功地以 1、2 或 3 个字节表示任何 UNICODE 字符:

    UriFile = proj.fileName().encode('utf8')
    

    【讨论】:

      【解决方案2】:

      感谢您的回答,

      我在python代码中用unicode替换str找到了答案,请看下面的代码。

      from os import startfile; 
      proj = QgsProject.instance();
      UriFile = unicode(proj.fileName()); 
      img = '[% "pad" %]'; 
      Path = unicode(os.path.dirname(UriFile)); 
      startfile(Path+img)
      
      from os import startfile; 
      proj = QgsProject.instance();
      UriFile = unicode(proj.fileName()); 
      img = '[% "pad" %]'; 
      Path = unicode(os.path.dirname(UriFile)); 
      startfile(Path+img)
      

      【讨论】:

        【解决方案3】:

        经过大量搜索,我找不到方法,但我可以忽略它

        OBJECT.encode('ascii', 'ignore')

        【讨论】:

          猜你喜欢
          • 2018-05-04
          • 2023-03-24
          • 2018-05-05
          • 2018-04-15
          • 2013-04-21
          • 2015-04-13
          • 2017-02-19
          • 2018-07-07
          相关资源
          最近更新 更多