在window下使用gemsim.models.word2vec.LineSentence加载中文维基百科语料库(已分词)时报如下错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byte

  这种编码问题真的很让人头疼,这种问题都是出现在xxx.decode("utf-8")的时候,所以接下来我们来看看gensim中的源码:

class LineSentence(object):
"""Iterate over a file that contains sentences: one line = one sentence.
Words must be already preprocessed and separated by whitespace. """
def __init__(self, source, max_sentence_length=MAX_WORDS_IN_BATCH, limit=None):
""" Parameters
----------
source : string or a file-like object
Path to the file on disk, or an already-open file object (must support `seek(0)`).
limit : int or None
Clip the file to the first `limit` lines. Do no clipping if `limit is None` (the default). Examples
--------
.. sourcecode:: pycon >>> from gensim.test.utils import datapath
>>> sentences = LineSentence(datapath('lee_background.cor'))
>>> for sentence in sentences:
... pass """
self.source = source
self.max_sentence_length = max_sentence_length
self.limit = limit def __iter__(self):
"""Iterate through the lines in the source."""
try:
# Assume it is a file-like object and try treating it as such
# Things that don't have seek will trigger an exception
self.source.seek(0)
for line in itertools.islice(self.source, self.limit):
line = utils.to_unicode(line).split()
i = 0
while i < len(line):
yield line[i: i + self.max_sentence_length]
i += self.max_sentence_length
except AttributeError:
# If it didn't work like a file, use it as a string filename
with utils.smart_open(self.source) as fin:
for line in itertools.islice(fin, self.limit):
line = utils.to_unicode(line).split()
i = 0
while i < len(line):
yield line[i: i + self.max_sentence_length]
i += self.max_sentence_length

  从源码中可以看到__iter__方法让LineSentence成为了一个可迭代的对象,而且文件读取的方法也都定义在__iter__方法中。一般我们输入的source参数都是一个文件路径(也就是一个字符串形式),因此在try时,self.source.seek(0)会报“字符串没有seek方法”的错,所以真正执行的代码是在except中。

  接下来我们有两种方法来解决我们的问题:

  1)from gensim import utils

    utils.samrt_open(url, mode="rb", **kw)

    在源码中用utils.smart_open()方法打开文件时默认是用二进制的形式打开的,可以将mode=“rb” 改成mode=“r”。

  2)from gensim import utils

    utils.to_unicode(text, encoding='utf8', errors='strict')

    在源码中在decode("utf8")时,其默认errors=“strict”, 可以将其改成errors="ignore"。即utils.to_unicode(line, errors="ignore")

  不过建议大家不要直接在源码上修改,可以直接将源码复制下来,例如:

import logging
import itertools
import gensim
from gensim.models import word2vec
from gensim import utils logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) class LineSentence(object):
"""Iterate over a file that contains sentences: one line = one sentence.
Words must be already preprocessed and separated by whitespace. """
def __init__(self, source, max_sentence_length=10000, limit=None):
""" Parameters
----------
source : string or a file-like object
Path to the file on disk, or an already-open file object (must support `seek(0)`).
limit : int or None
Clip the file to the first `limit` lines. Do no clipping if `limit is None` (the default). Examples
--------
.. sourcecode:: pycon >>> from gensim.test.utils import datapath
>>> sentences = LineSentence(datapath('lee_background.cor'))
>>> for sentence in sentences:
... pass """
self.source = source
self.max_sentence_length = max_sentence_length
self.limit = limit def __iter__(self):
"""Iterate through the lines in the source."""
try:
# Assume it is a file-like object and try treating it as such
# Things that don't have seek will trigger an exception
self.source.seek(0)
for line in itertools.islice(self.source, self.limit):
line = utils.to_unicode(line).split()
i = 0
while i < len(line):
yield line[i: i + self.max_sentence_length]
i += self.max_sentence_length
except AttributeError:
# If it didn't work like a file, use it as a string filename
with utils.smart_open(self.source, mode="r") as fin:
for line in itertools.islice(fin, self.limit):
line = utils.to_unicode(line).split()
i = 0
while i < len(line):
yield line[i: i + self.max_sentence_length]
i += self.max_sentence_length our_sentences = LineSentence("./zhwiki_token.txt")
model = gensim.models.Word2Vec(our_sentences, size=200, iter=30) # 大语料,用CBOW,适当的增大迭代次数
# model.save(save_model_file)
model.save("./mathWord2Vec" + ".model") # 以该形式保存模型以便之后可以继续增量训练

解决在使用gensim.models.word2vec.LineSentence加载语料库时报错 UnicodeDecodeError: 'utf-8' codec can't decode byte......的问题的更多相关文章

  1. VS加载项目时报错 尚未配置为Web项目XXXX指定的本地IIS

    网上找的几个方法都不行 最后自己解决了.首先打开该项目得csproj文件,找到<ProjectExtensions>这个标签,是在最后部分,然后把<UseIIS>True< ...

  2. OpenCV使用:加载图片时报错 0x00007FFC1084A839 处(位于 test1.exe 中)有未经处理的异常: Microsoft C++ 异常: cv::Exception,位于内存位置 0x00000026ABAFF1A8 处。

    加载图片代码为: #include<iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgu ...

  3. Visual studio加载项目时报错 尚未配置为Web项目XXXX指定的本地IIS,需要配置虚拟目录。解决办法。

    在SVN上下载工程项目.使用visual studio打开时,出现如下提示: 查找相关资料,解决办法如下: 使用记事本打开工程目录下的.csproj文件.把<UseIIS>False< ...

  4. 解决vs2013下创建的python文件,到其他平台(如linux)下中文乱码(或运行时报SyntaxError: (unicode error) 'utf-8' codec can't decode byte...)

    Vs2013中创建python文件,在文件中没输入中文时,编码为utf-8的,如图 接着,在里面输入几行中文后,再次用notepad++查看其编码如下,在vs下运行也报错(用cmd运行就不会): 根据 ...

  5. moviepy用VideoFileClip加载视频时报UnicodeDecodeError: utf-8 codec cant decode byte invalid start byte错误

    专栏:Python基础教程目录 专栏:使用PyQt开发图形界面Python应用 专栏:PyQt入门学习 老猿Python博文目录 老猿学5G博文目录 使用moviepy用: clip1 = Video ...

  6. 【技术贴】第二篇 :解决使用maven jetty启动后无法加载修改过后的静态资源

    之前写过第一篇:[技术贴]解决使用maven jetty启动后无法加载修改过后的静态资源 一直用着挺舒服的,直到今天,出现了又不能修改静态js,jsp等资源的现象.很是苦闷. 经过调错处理之后,发现是 ...

  7. 解决Vue刷新一瞬间出现样式未加载完或者出现Vue代码问题

    解决Vue刷新一瞬间出现样式未加载完或者出现Vue代码问题: <style> [v-cloak]{ display: none; } </style> <div id=& ...

  8. 解决Torch.load()错误信息: UnicodeDecodeError: 'ascii' codec can't decode byte 0x8d in position 0: ordinal not in range(128)

    使用PyTorch跑pretrained预训练模型的时候,发现在加载数据的时候会报错,具体错误信息如下: File "main.py", line 238, in main_wor ...

  9. moviepy用VideoFileClip加载视频时报UnicodeDecodeError: codec cant decode ,No mapping character 错误

    专栏:Python基础教程目录 专栏:使用PyQt开发图形界面Python应用 专栏:PyQt入门学习 老猿Python博文目录 老猿学5G博文目录 昨天处理视频时出现了解码错误,通过修改ffmpeg ...

随机推荐

  1. pytest框架之命令行参数1

    前言 pytest是一款强大的python自动化测试工具,可以胜任各种类型或者级别的软件测试工作.pytest提供了丰富的功能,包括assert重写,第三方插件,以及其他测试工具无法比拟的fixtur ...

  2. Ubuntu 18.04.1 LTS + kolla-ansible 部署 openstack Rocky all-in-one 环境

    1. kolla 项目介绍 简介 kolla 的使命是为 openstack 云平台提供生产级别的.开箱即用的自动化部署能力. kolla 要实现 openetack 部署分为两步,第一步是制作 do ...

  3. 【深度学习】--DCGAN从入门到实例应用

    一.前述 DCGAN就是Deep Concolutions应用到GAN上,但是和传统的卷积应用还有一些区别,最大的区别就是没有池化层.本文将详细分析卷积在GAN上的应用. 二.具体 1.DCGAN和传 ...

  4. [开源]WinForm 控件使用总结

    背景 都2019年了,还在用WinForm吗?哈哈,其实我也没在用,都是很多年前一些项目积累,所以代码写的有些屎,之所以开源出来,希望能给大家有所帮助,喜欢的话给 一个Star以资鼓励~: 具体代码: ...

  5. Asp.Net Core 轻松学-利用文件监视进行快速测试开发

    前言     在进行 Asp.Net Core 应用程序开发过程中,通常的做法是先把业务代码开发完成,然后建立单元测试,最后进入本地系统集成测试:在这个过程中,程序员的大部分时间几乎都花费在开发.运行 ...

  6. jquery获取元素(父级的兄弟元素的子元素)

    一.获取父级元素 使用jquery获取父级元素: parent() 例如:$(this).parent('ul'); 二.获取同级元素 使用jquery获取同级元素:siblings() 例如:$(t ...

  7. 【技术解析】如何用Docker实现SequoiaDB集群的快速部署

    1. 背景 以Docker和Rocket为代表的容器技术现在正变得越来越流行,它改变着公司和用户创建.发布.运行分布式应用的方式,在未来5年将给云计算行业带来它应有的价值.它的诱人之处在于: 1)资源 ...

  8. 树莓派SSH连接快速教程

    树莓派系统一般都默认自带ssh 1.首先检查是否安装ssh没 dpkg - l | grep openssh 如果出现几个openssh-xxx,说明你已经安装了 如果没有 2.SSH服务安装 sud ...

  9. C#连接基于Java开发IM——Openfire

    Openfire简介    Openfire 是开源的.基于可拓展通讯和表示协议(XMPP).采用Java编程语言开发的实时协作服务器.Openfire的效率很高,单台服务器可支持上万并发用户.    ...

  10. MyBatis缓存策略

    MyBatis 提供了一级缓存和二级缓存策略,一级缓存是作用在SqlSession级别上的,而二级缓存则是作用在Mapper级别上的( 即作用在 namespace上),MyBatis 默认是开启的一 ...