18-(unicode error) 'unicodeescape' codec can't decode bytes in position 16-17: truncated
Posted zhumengdexiaobai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了18-(unicode error) 'unicodeescape' codec can't decode bytes in position 16-17: truncated相关的知识,希望对你有一定的参考价值。
读取文件时碰到问题:
1.(unicode error) ‘unicodeescape‘ codec can‘t decode bytes in position 16-17: truncated uXXXX escape
在stackoverflow上找到了答案,就是将在路径字符串前加 r : 去掉转义:
path = r‘C:UserssssDesktophanyucidian.txt‘ with open(path, ‘rb‘) as f: str = f.read().decode(‘gb18030‘)
2.UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xa1 in position 0
Python 编码中编码解码的问题,我这个错误就是‘utf-8’不能解码位置0的那个字节(0xa1),也就是这个字节超出了utf-8的表示范围了
解决办法换种编码方式:
import re def getHanYuCi(str): p = re.compile(r‘【.*?】‘) rt = p.findall(str) #print(str[0:1000]) return rt path = r‘C:UserssssDesktophanyucidian.txt‘ with open(path, ‘rb‘) as f: str = f.read().decode(‘gb18030‘) rt = getHanYuCi(str) print(‘+++++++++++++‘) print(len(rt)) #print(rt) # 由于rt特别大,直接print不会读出任何东西,但只读某一段时可以读出来 print(rt[1:10])
以上是关于18-(unicode error) 'unicodeescape' codec can't decode bytes in position 16-17: truncated的主要内容,如果未能解决你的问题,请参考以下文章
python3:(unicode error) 'utf-8' codec can't decode
python 3中使用Unicode字符串操作符u的结果为啥是这样的?
Python_报错:SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in posit