Python 除了 UnicodeError?

新手上路,请多包涵

在我的代码中,我不断收到此错误…

 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 390: character maps to <undefined>

我试图放置一个 UnicodeError 和 UnicodeEncodeError 除外但没有任何效果,问题是它是用户输入所以我无法控制他们放置的内容所以我需要所有编码错误来显示一个打印错误而不是崩溃程序.. .

 try:
    argslistcheck = argslist[0]
    if argslistcheck[0:7] != "http://":
        argslist[0] = "http://" + argslist[0]
    with urllib.request.urlopen(argslist[0]) as url:
        source = url.read()
        source = str(source, "utf8")
    except urllib.error.URLError:
        print("Couln't connect")
        source = ""
    except UnicodeEncodeError:
        print("There was an error encrypting...")
        source = ""

追溯:

 Traceback (most recent call last):
  ..... things leading up to error
  File "C:\path", line 99, in grab print(source)
  File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 390: character maps to <undefined>

原文由 TrevorPeyton 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 458
2 个回答

试试这个:

source = str(source, encoding='utf-8', errors = 'ignore')

或者看看 这篇文章的问题

原文由 chirinosky 发布,翻译遵循 CC BY-SA 3.0 许可协议

你的 打印 失败了。您的 Windows 控制台不支持打印 UTF-8,您需要更改代码页:

 chcp 65001

这是 _Windows 命令_,而不是 python 命令。您可能还需要切换字体,Lucida Sans Console 是一种 Unicode 字体,可以处理更多字形。

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题