UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xbc in position 7291: invalid start byte

遇到这种问题,就是文件编码的缘故。
最好的解决方式就是,以二进制的方式读,然后以正确的编码重新encode它。
示例:

#我想要utf-8格式的
with open('words.vec','rb') as f:
    lines=[l.decode('utf8','ignore') for l in f.readlines()]

如果还是有乱码,可以这样玩:

import re
# 判断一个字符串是否是小数
def IsFloat(s):
    pattern = '^-?\d+\.?\d*$'  # 匹配数字: 从头开始匹配 -0或1次 数字1或多次 .0或1次 数字0或多次 匹配到字符串末尾
    match = re.match(pattern, s)
    return match != None
word_embeddings = {}
with open('words.vec','rb') as f:
    lines=[l.decode('utf8','ignore') for l in f.readlines()]
lines=lines[1:]
for line in lines:
    if len(line)<10:
        break
    data = line.strip().split()
    name=str(data[0])
    content=data[1:]
    con=[]
    for i in content:
        if not IsFloat(i):
            break
        con.append(float(i))
    word_embeddings[name] = con        
print(len(word_embeddings))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值