除了 UnicodeError 之外的 Python? [英] Python except for UnicodeError?

查看:42
本文介绍了除了 UnicodeError 之外的 Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my code I keep getting this error...

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

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

I tried to put an except for UnicodeError and UnicodeEncodeError but nothing works, the problem is it's the users input so I can't control what they put so I need all encode errors to display a print that says error instead of crashing the program...

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>

推荐答案

试试这个:

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

或者看看这篇文章的问题.

这篇关于除了 UnicodeError 之外的 Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆