码迷,mamicode.com
首页 > 其他好文 > 详细

18-(unicode error) 'unicodeescape' codec can't decode bytes in position 16-17: truncated \uXXXX escape

时间:2018-09-17 19:43:36      阅读:2788      评论:0      收藏:0      [点我收藏+]

标签:dede   pen   truncated   python 编码   答案   str   pytho   open   cell   

读取文件时碰到问题:

1.(unicode error) ‘unicodeescape‘ codec can‘t decode bytes in position 16-17: truncated \uXXXX escape

在stackoverflow上找到了答案,就是将在路径字符串前加 r : 去掉转义:

path = r‘C:\Users\sss\Desktop\hanyucidian.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:\Users\sss\Desktop\hanyucidian.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 \uXXXX escape

标签:dede   pen   truncated   python 编码   答案   str   pytho   open   cell   

原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/9663375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!