关于Python-UnicodeDecodeError,无效的继续字节和无效的pythonsdk的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Eclipse运行python代码报错:Un
关于Python-UnicodeDecodeError,无效的继续字节和无效的pythonsdk的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Eclipse 运行python代码报错: UnicodeDecodeError: ''utf8'' codec can''t decode byte、mysql-connector-python 取二进制字节时报错 UnicodeDecodeError:''utf-8'' codec can''t decode byte 0xb...、pip install和UnicodeDecodeError:'utf-8'编解码器无法解码位置9的字节0xe0:无效的连续字节、Python 3 UnicodeDecodeError-如何调试UnicodeDecodeError?等相关知识的信息别忘了在本站进行查找喔。
本文目录一览:- Python-UnicodeDecodeError,无效的继续字节(无效的pythonsdk)
- Eclipse 运行python代码报错: UnicodeDecodeError: ''utf8'' codec can''t decode byte
- mysql-connector-python 取二进制字节时报错 UnicodeDecodeError:''utf-8'' codec can''t decode byte 0xb...
- pip install和UnicodeDecodeError:'utf-8'编解码器无法解码位置9的字节0xe0:无效的连续字节
- Python 3 UnicodeDecodeError-如何调试UnicodeDecodeError?
Python-UnicodeDecodeError,无效的继续字节(无效的pythonsdk)
为什么以下项目失败?为什么使用“ latin-1”
编解码器成功?
o = "a test of \xe9 char" #I want this to remain a string as this is what I am receivingv = o.decode("utf-8")
结果是:
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: ''utf8'' codec can''t decode byte 0xe9 in position 10: invalid continuation byte
答案1
小编典典在二进制文件中,0xE9
看起来像1110 1001
。如果你在Wikipedia
上读到有关UTF-8
的信息,你会看到,这样的字节必须后面跟两个格式10xx xxxx
。因此,例如:
>>> b''\xe9\x80\x80''.decode(''utf-8'')u''\u9000''
但这仅仅是例外的机械原因。在这种情况下,你几乎可以肯定用拉丁文1编码了一个字符串。你可以看到UTF-8和拉丁文1看起来如何不同:
>>> u''\xe9''.encode(''utf-8'')b''\xc3\xa9''>>> u''\xe9''.encode(''latin-1'')b''\xe9''
(请注意,我在这里混合使用了Python 2和3表示形式。输入在任何版本的Python中均有效,但是你的Python解释器不太可能以这种方式同时显示unicode
和字节字符串。)
答案2
小编典典当我尝试通过pandas read_csv
方法打开一个csv文件时遇到了相同的错误。
解决方案是将编码更改为“ latin-1”
:
pd.read_csv(''ml-100k/u.item'', sep=''|'', names=m_cols , encoding=''latin-1'')
Eclipse 运行python代码报错: UnicodeDecodeError: ''utf8'' codec can''t decode byte
错误信息如下:
网上报这个错误的原因有很多,包括:
- 脚本本身不是使用UTF-8编码的,需要转成utf-8编码
- 脚本的头部需要声明为:utf-8 编码
- 工程路径中包含中文字符也会报这个错误,因为python会读取windows中工程路径,而windows中的编码一般都是亲生的gbk类编码不太容易修改,所以这种情况下需要将你的工程移到没有中文字符的目录下,然后在重新导入.
mysql-connector-python 取二进制字节时报错 UnicodeDecodeError:''utf-8'' codec can''t decode byte 0xb...
在储存用户密码时,我使用了 hmac 算法对用户密码加密,加密出来的 hash 值是一个二进制字节串,我把这个字节串存到 mysql 的 password 字段,password 字段的数据类型是 varbinary。
在验证用户密码时,我把用户输入的密码经过同样的 hmac 算法得到 hash 值,然后从数据库 password 字段的字节串取出来,比较两个字节串是否相等。
在开发环境中,这样做没有任何问题,但是当我把代码部署到 centos7 的服务器上时,存 password 字节串没有问题,却在取 password 字段的字节串时出现了 UnicodeDecodeError:''utf-8'' codec can''t decode byte 0xb0 in position 0 的错误。
其实仔细看一下,这个问题的根源在于 mysqlconnector 试图将二进制字节解码为 unicode,也就是字符串,但其实我们是不需要这样做的,我们只需要将这个二进制字节完完整整地取出来。
因为我的生产和开发环境的 mysql 版本不同,因此开发环境中,不需要任何设置 mysqlconnector 就自动不会对二进制字节进行解码。我们现在要做的就很简单,阻止 mysqlconnector 解码二进制字节。
查看 mysqlconnector 的源码,在 cursor_cext.py 找到 CMySQLCursor 类,这个类的实例就是我们用的 cursor,但是这个类的 fetchone、fetchall、fetchmany 等函数都不接受编码相关的参数,因此可能不能通过设置 cursor 来解决,于是我又在官网上找到了 connect(连接数据库的函数)的配置参数说明
找到 use_unicode 一项,这个参数控制 mysqlconnector 在取数据的时候会不会将二进制字节解码为字符串,它的默认值是 True。用法如下
mysql.connector.connect(**config,use_unicode=False)
这样取出来的数据类型为 <class ''bytes''>,这个错误也不会出现了
pip install和UnicodeDecodeError:'utf-8'编解码器无法解码位置9的字节0xe0:无效的连续字节
尝试安装:
pip install python-binance
结果:
Exception:Traceback (most recent call last): File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 73, in console_to_str return s.decode(sys.__stdout__.encoding)UnicodeDecodeError: ''utf-8'' codec can''t decode byte 0xe0 in position 9: invalid continuation byteDuring handling of the above exception, another exception occurred:Traceback (most recent call last): File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 634, in _prepare_file abstract_dist.prep_for_dist() File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 129, in prep_for_dist self.req_to_install.run_egg_info() File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 439, in run_egg_info command_desc=''python setup.py egg_info'') File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\utils\__init__.py", line 676, in call_subprocess line = console_to_str(proc.stdout.readline()) File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 75, in console_to_str return s.decode(''utf_8'')UnicodeDecodeError: ''utf-8'' codec can''t decode byte 0xe0 in position 9: invalid continuation byte
怎么解决?
答案1
小编典典好的…
- 由于错误在我的文件中:
c:\ users \анна\ appdata \ local \ programs \ python \ python36 \ lib \
site-packages \ pip \ compat__init __。py
问题文件夹为“ анна ”,即 cp1251
第一个解决方案是找到如何重命名用户的文件夹。(除了重新安装操作系统外)。到带有拉丁字母的文件夹
文件 compat__init__.py中 的第二个路径-替换
return s.decode(sys.__stdout__.encoding)
- 进入
return s.decode(''cp1251'')
当然,您需要知道所使用的编码。对我来说是 cp1251 ,对您来说可以是 拉丁语 (例如)。替换文件后-一切都安装成功!
谢谢2考伯特
Python 3 UnicodeDecodeError-如何调试UnicodeDecodeError?
我有一个文本文件,发布者(美国证券交易委员会)断言该文本文件以UTF-8编码(https://www.sec.gov/files/aqfs.pdf,第4节)。我正在使用以下代码处理代码行:
def tags(filename): """Yield Tag instances from tag.txt.""" with codecs.open(filename, ''r'', encoding=''utf-8'', errors=''strict'') as f: fields = f.readline().strip().split(''\t'') for line in f.readlines(): yield process_tag_record(fields, line)
我收到以下错误:
Traceback (most recent call last): File "/home/randm/Projects/finance/secxbrl.py", line 151, in <module> main() File "/home/randm/Projects/finance/secxbrl.py", line 143, in main all_tags = list(tags("tag.txt")) File "/home/randm/Projects/finance/secxbrl.py", line 109, in tags content = f.read() File "/home/randm/Libraries/anaconda3/lib/python3.6/codecs.py", line 698, in read return self.reader.read(size) File "/home/randm/Libraries/anaconda3/lib/python3.6/codecs.py", line 501, in read newchars, decodedbytes = self.decode(data, self.errors)UnicodeDecodeError: ''utf-8'' codec can''t decode byte 0xad in position 3583587: invalid start byte
鉴于我可能无法回到SEC并告诉他们它们包含的文件似乎未采用UTF-8编码,我应该如何调试和捕获此错误?
我尝试了什么
我对文件进行了十六进制转储,发现有问题的文本是文本``非现金投资的补充披露’‘。如果我将有问题的字节解码为十六进制代码点(即“ U +
00AD”),则在上下文中是有意义的,因为它是软连字符。但是以下似乎无效:
Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linuxType "help", "copyright", "credits" or "license" for more information.>>> b"\x41".decode("utf-8")''A''>>> b"\xad".decode("utf-8")Traceback (most recent call last): File "<stdin>", line 1, in <module>UnicodeDecodeError: ''utf-8'' codec cant decode byte 0xad in position 0: invalid start byte>>> b"\xc2ad".decode("utf-8")Traceback (most recent call last): File "<stdin>", line 1, in <module>UnicodeDecodeError: ''utf-8'' codec cant decode byte 0xc2 in position 0: invalid continuation byte
我用过了errors=''replace''
,这似乎过去了。但我想了解一下,如果我尝试将其插入数据库中会发生什么。
编辑添加十六进制转储:
0036ae40 31 09 09 09 09 53 55 50 50 4c 45 4d 45 4e 54 41 |1....SUPPLEMENTA|0036ae50 4c 20 44 49 53 43 4c 4f 53 55 52 45 20 4f 46 20 |L DISCLOSURE OF |0036ae60 4e 4f 4e ad 43 41 53 48 20 49 4e 56 45 53 54 49 |NON.CASH INVESTI|0036ae70 4e 47 20 41 4e 44 20 46 49 4e 41 4e 43 49 4e 47 |NG AND FINANCING|0036ae80 20 41 43 54 49 56 49 54 49 45 53 3a 09 0a 50 72 | ACTIVITIES:..Pr|
答案1
小编典典您的数据文件已损坏。如果该字符确实是U + 00AD SOFT
HYPHEN,那么您缺少一个0xC2字节:
>>> ''\u00ad''.encode(''utf8'')b''\xc2\xad''
在以0xAD结尾的所有可能的UTF-8编码中,软连字符确实最有意义。但是,它指示 可能 缺少其他字节的数据集。您碰巧碰到了一个重要事件。
我将返回此数据集的源,并验证下载时文件未损坏。否则,error=''replace''
如果没有分隔符(制表符,换行符等)缺失,则使用是可行的解决方法。
另一种可能性是SEC实际上对文件使用了 不同的
编码。例如,在Windows代码页1252和Latin-1中,0xAD
是软连字符的正确编码。确实,当我直接下载相同的数据集(警告,链接了大的ZIP文件)并打开时tags.txt
,我无法将数据解码为UTF-8:
>>> open(''/tmp/2017q1/tag.txt'', encoding=''utf8'').read()Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/.../lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final)UnicodeDecodeError: ''utf-8'' codec can''t decode byte 0xad in position 3583587: invalid start byte>>> from pprint import pprint>>> f = open(''/tmp/2017q1/tag.txt'', ''rb'')>>> f.seek(3583550)3583550>>> pprint(f.read(100))(b''1\t1\t\t\t\tSUPPLEMENTAL DISCLOSURE OF NON\xadCASH INVESTING AND FINANCING A'' b''CTIVITIES:\t\nProceedsFromSaleOfIn'')
文件中有两个这样的非ASCII字符:
>>> f.seek(0)0>>> pprint([l for l in f if any(b > 127 for b in l)])[b''SupplementalDisclosureOfNoncashInvestingAndFinancingActivitiesAbstract\t0'' b''001654954-17-000551\t1\t1\t\t\t\tSUPPLEMENTAL DISCLOSURE OF NON\xadCASH I'' b''NVESTING AND FINANCING ACTIVITIES:\t\n'', b''HotelKranichhheMember\t0001558370-17-001446\t1\t0\tmember\tD\t\tHotel Krani'' b''chhhe [Member]\tRepresents information pertaining to Hotel Kranichh\xf6h'' b''e.\n'']
Hotel Kranichh\xf6he
HotelKranichhöhe 被解码为Latin-1 。
文件中还有几对0xC1 / 0xD1对:
>>> f.seek(0)0>>> quotes = [l for l in f if any(b in {0x1C, 0x1D} for b in l)]>>> quotes[0].split(b''\t'')[-1][50:130]b''Temporary Payroll Tax Cut Continuation Act of 2011 (\x1cTCCA\x1d) recognized during th''>>> quotes[1].split(b''\t'')[-1][50:130]b''ributory defined benefit pension plan (the \x1cAetna Pension Plan\x1d) to allow certai''
我敢打赌那些实际上是U + 201C左双引号和U +
201D右双引号;注意1C
和1D
部分。似乎他们的编码器似乎采用了UTF-16并去除了所有高字节,而不是正确地编码为UTF-8!
没有与Python中没有编解码器出货将编码''\u201C\u201D''
来b''\x1C\x1D''
,使这一切更可能的是,美国证券交易委员会已经把事情弄糟了编码过程中的某个地方。实际上,还有0x13和0x14字符(可能是
en 和 em 破折号)(U + 2013和U +
2014),以及几乎可以肯定是单引号的0x19字节(U +
2019)。完整图片所缺少的只是一个0x18字节来表示U +
2018。
如果我们假设编码已损坏,则可以尝试修复。以下代码将读取文件并解决引号问题,并假设其余数据不使用除引号之外的Latin-1之外的字符:
_map = { # dashes 0x13: ''\u2013'', 0x14: ''\u2014'', # single quotes 0x18: ''\u2018'', 0x19: ''\u2019'', # double quotes 0x1c: ''\u201c'', 0x1d: ''\u201d'',}def repair(line, _map=_map): """Repair mis-encoded SEC data. Assumes line was decoded as Latin-1""" return line.translate(_map)
然后将其应用于您阅读的行:
with open(filename, ''r'', encoding=''latin-1'') as f: repaired = map(repair, f) fields = next(repaired).strip().split(''\t'') for line in repaired: yield process_tag_record(fields, line)
另外,解决您的已发布代码,使Python变得比预期更难工作。不要用codecs.open()
; 那是已知问题的旧代码,并且比新的Python 3 I /
O层慢。只需使用open()
。不要使用f.readlines()
; 您无需在此处将整个文件读入列表。只需直接遍历文件即可:
def tags(filename): """Yield Tag instances from tag.txt.""" with open(filename, ''r'', encoding=''utf-8'', errors=''strict'') as f: fields = next(f).strip().split(''\t'') for line in f: yield process_tag_record(fields, line)
如果process_tag_record
还在选项卡上拆分,请使用一个csv.reader()
对象,并避免手动拆分每一行:
import csvdef tags(filename): """Yield Tag instances from tag.txt.""" with open(filename, ''r'', encoding=''utf-8'', errors=''strict'') as f: reader = csv.reader(f, delimiter=''\t'') fields = next(reader) for row in reader: yield process_tag_record(fields, row)
如果process_tag_record
将fields
列表与其中的值组合在一起row
以形成字典,请csv.DictReader()
改用:
def tags(filename): """Yield Tag instances from tag.txt.""" with open(filename, ''r'', encoding=''utf-8'', errors=''strict'') as f: reader = csv.DictReader(f, delimiter=''\t'') # first row is used as keys for the dictionary, no need to read fields manually. yield from reader
我们今天的关于Python-UnicodeDecodeError,无效的继续字节和无效的pythonsdk的分享就到这里,谢谢您的阅读,如果想了解更多关于Eclipse 运行python代码报错: UnicodeDecodeError: ''utf8'' codec can''t decode byte、mysql-connector-python 取二进制字节时报错 UnicodeDecodeError:''utf-8'' codec can''t decode byte 0xb...、pip install和UnicodeDecodeError:'utf-8'编解码器无法解码位置9的字节0xe0:无效的连续字节、Python 3 UnicodeDecodeError-如何调试UnicodeDecodeError?的相关信息,可以在本站进行搜索。
本文标签: