Python中如何处理UnicodeError?

5 投票
4 回答
27663 浏览
提问于 2025-04-17 16:58

在我的代码中,我一直遇到这个错误...

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>

4 个回答

3

试试这个方法来替代 str() 函数:source = source.encode('UTF-8')

5

你的 print 出现问题了。你的Windows控制台不支持打印UTF-8格式的内容,你需要更改代码页:

chcp 65001

这是一条 Windows命令,而不是Python命令。你可能还需要更换字体,Lucida Sans Console是一种支持更多字符的Unicode字体。

6

试试这个方法:

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

或者可以看看 这个帖子的问题

撰写回答