------------只要够努力,人生最坏的结局不过是大器晚成!!!

读取文件时碰到问题:

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])

  

   

posted on 2018-09-17 17:27  ystraw  阅读(307)  评论(0编辑  收藏  举报

不经一番切孤寒,怎得梅花扑鼻香