在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. Agent Job代理 执行SSIS Package

    摘要: 在使用Agent Job时, 运行SSIS包的Run as账号,必须有SSIS中connection manager的连接权限. 如果没有连接权限,可以用创建proxy账号,并确保proxy账 ...

  2. CYQ.Data 对于分布式缓存Redis、MemCache高可用的改进及性能测试

    背景: 随着.NET Core 在 Linux 下的热动,相信动不动就要分布式或集群的应用的需求,会慢慢火起来. 所以这段时间一直在研究和思考分布式集群的问题,同时也在思考把几个框架的思维相对提升到这 ...

  3. Linux2:Linux目录结构

    Linux目录图 进入根目录,使用ll命令看一下Linux整个根目录图: 这里面所有的目录都是买完服务器之后最初始的目录,没有进过任何加工.Linux以树的结构组织所有目录,用一张图表示一下Linux ...

  4. java.lang.ClassNotFoundException: org.I0Itec.zkclient.IZkStateListener异常解决

    在启动Dubbo项目时,出现该异常 java.lang.ClassNotFoundException: org.I0Itec.zkclient.IZkStateListener 解决,引入 <d ...

  5. SUSE12SP3-Zookeeper安装

    直接使用root账号 1.zookeeper安装 将zookeeper-3.4.13.tar.gz安装包放置指定目录 sudo tar -zxvf zookeeper-3.4.13.tar.gz -C ...

  6. 认识音频格式-Au (NeXT/Sun)

    音频格式比较多, Au音频格式是一种被sun微处理器公司发明的一种简单的音频编码格式.日后一直在NEXT系统上使用,后面就演变成了一种标准的音频编码格式.目前很多音频设备上都支持这种编码格式.这种编码 ...

  7. ubuntu 安装 npm、nodejs 各种问题

    nodejs let notifier = require('update-notifier')({pkg}) 报错 先卸载nodejs,然后安装稳定最新版 # apt-get remove node ...

  8. 前后端同学,必会的Linux常用基础命令

    无论是前端还是后端同学,一些常用的linux命令还是必须要掌握的.发布版本.查看日志等等都会用到.以下是我简单的总结了一些简单又常用的命令,欢迎大家补充.希望能帮助到大家 本文首发于公众号 程序员共成 ...

  9. idea git提交时候提示 --author 'java_suisui' is not 'Name ' and matches no existing author

    今天使用idea修改git项目的作者信息,提交时遇到错误: 0 files committed, 1 file failed to commit: test --author 'java_suisui ...

  10. 六大设计原则(四)ISP接口隔离原则(上)

    ISP的定义 首先明确接口定义 实例接口 我们在Java中,一个类用New关键字来创建一个实例.抛开Java语言我们其实也可以称为接口.假设Person zhangsan = new Person() ...