解决gensim模型加载错误:UnicodeDecodeError: 'utf-8' codec can't decode bytes in position。。。的方法

NLP领域最出名的python库之一就是gensim,该库包含了常见的word2vec模型,而我们在使用这些模型进行embedding的时候可会出现如下的编码问题:

UnicodeDecodeError: 'utf-8' codec can't decode bytes in position

这个错误在提示加载模型时出现了编码错误,即在某一个位置的字节是无法编码的,并会给出相应的的位置。
这个问题在gensim官方github中也有反馈,并且作者统一给出了解决方法:

Answer: The strings (words) stored in your model are not valid utf8. By default, gensim decodes the words using the strict encoding settings, which results in the above exception whenever an invalid utf8 sequence is encountered.
The fix is on your side and it is to either:
a) Store your model using a program that understands unicode and utf8 (such as gensim). Some C and Java word2vec tools are known to truncate the strings at byte boundaries, which can result in cutting a multi-byte utf8 character in half, making it non-valid utf8, leading to this error.
b) Set the unicode_errors flag when running load_word2vec_model, e.g. load_word2vec_model(…, unicode_errors=‘ignore’). Note that this silences the error, but the utf8 problem is still there – invalid utf8 characters will just be ignored in this case.

第一种方法告诉了使用者可以用C和JAVA的相关工具去处文本中的无效编码字符;
第二种方法建议在load_word2vec_model函数中设置参数unicode_errors=‘ignore’,可以暂时忽略这个错误。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值