读取文件时碰到问题:
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
原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/9663375.html
时间: 2024-10-10 16:43:35