在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. AD用户属性:UserPrincipalName与SamAccountName的差别

    在我们日常工作中或者日常针对AD进行自动化开发的过程中,我们都会对UserPrincipalName与SamAccountName产生疑惑,毕竟很多时候大家都把这两个属性值理解为同一个概念,至于为什么 ...

  2. java中强大的免费的集成开发环境(IDE)eclipse的使用技巧及注意事项

    1调整字体,window->prefernce->Appereance->colors and fonts->Basic->Text font双击即可进行编辑 2.设置行 ...

  3. 在linux系统部署Svn

      步骤一:安装subversion 1) 连接xshell,在xshell输入命令:yum install subversion 2) 查看安装svn服务的版本:svnserve --version ...

  4. ThinkPHP5.1 + tufanbarisyildirim 解析apk

    摘要 对于apk,我可以说只会安装,并不知道其中有什么内容需要记录下来.这次公司做一个关于电视机顶盒的项目.对于这个陌生的项目,刚开始真是一脸懵逼,完全不知道如何下手. 因为这类的项目完全没有接触过, ...

  5. 团队选题报告(bull beer)

    一.团队成员及分工 团队名称:bull beer 团队成员: 黄文东:选题报告word撰写 沈培:原型设计,博客撰写,ppt制作 邓泽中:住院 刘帅:查找相关资料 二.选题报告内容 项目名称:学费管理 ...

  6. 面向对象(__str__和__repr__方法)

    #Author : Kelvin #Date : 2019/1/21 16:19 class App: def __init__(self,name): self.name=name # def __ ...

  7. 前端笔记之JavaScript面向对象(一)Object&函数上下文&构造函数&原型链

    一.对象(Object) 1.1 认识对象 对象在JS中狭义对象.广义对象两种. 广义:相当于宏观概念,是狭义内容的升华,高度的提升,范围的拓展.狭义:相当于微观概念,什么是“狭”?因为内容狭隘具体, ...

  8. 微信小程序 Request faild 请求后台失败

    首先确认你的域名和ssl证书是否配置完成. 如果后台没有进行域名配置,先去配置一个有效的备案的自持https的域名. 1.建议备案超过24小时 2.ssl证书可以直接采用阿里云的免费证书   进行ss ...

  9. Scrum Mastery:有效利用组织的5个步骤

    组织以什么样的方式能最大限度的发挥Scrum的优势?组织在哪些方面阻碍了个人的发展?Scrum是一种能使业务变得敏捷的框架.而组织恰恰需要变得敏捷.只是,组织本身有时候并没有足够的能力来帮助Scrum ...

  10. 盘点 Python 中的那些冷知识(二)

    上一篇文章分享了 Python中的那些冷知识,地址在这里 盘点 Python 中的那些冷知识(一) 今天将接着分享!! 06. 默认参数最好不为可变对象 函数的参数分三种 可变参数 默认参数 关键字参 ...