在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. 使用exceljs时报错:no such file or directory

    最近使用exceljs生成excel并保存时,总是失败 await workbook.xlsx.writeFile(tep) .then(function () { context.result = ...

  2. Sitecore® 8.2 Professional Developer考试心得

    因工作原因入了Sitecore的坑.. 不了解Sitecore认证考试的同学请移步: http://www.cnblogs.com/edisonchou/archive/2018/08/17/9488 ...

  3. Oracle AWRSQRPT报告生成和性能分析

    我写的SQL调优专栏:https://blog.csdn.net/u014427391/article/category/8679315 对于局部的,比如某个页面列表sql,我们可以使用Oracle的 ...

  4. [Leetcode]450. Delete Node in a BST

    Given a root node reference of a BST and a key, delete the node with the given key in the BST. Retur ...

  5. 系列文章|OKR与敏捷(三):赋予团队自主权

    OKR与敏捷开发的原理有着相似之处,但已经使用敏捷的团队再用OKR感觉会显得多余.这种误解的根源就在于对这两种模式不够了解,运用得当的情况下,OKR和敏捷可以形成强强联合的效果,他们可以创造出以价值为 ...

  6. Python:游戏:贪吃蛇原理及代码实现

    一.游戏介绍 贪吃蛇是个非常简单的游戏,适合练手.先来看一下我的游戏截图: 玩法介绍:回车键:开始游戏空格键:暂停 / 继续↑↓←→方向键 或 WSAD 键:控制移动方向. 食物分红.绿.蓝三种,分别 ...

  7. SAMBA服务和FTP服务讲解(week3_day1)--技术流ken

    samba服务 Smb主要作为网络通信协议; Smb是基于cs架构: 完成Linux与windows之间的共享:linux与linux之间共享用NFS 第一步:安装samba [root@ken ~] ...

  8. DSAPI 导出EXEDLL函数到字符串

    EXE或者DLL写好了,要开始写函数说明文档了,可是有时里面的函数太多,怎么能自动列出来呢?在DSAPI中提供了该功能(目前没有做参数类型导出,以后有时间会添加). 先准备一个已经写好的EXE或DLL ...

  9. c#实战开发:以太坊钱包快速同步区块和钱包卡死解决方案 (三)

    首先以太坊默认的快速同步模式 我们需要先设置当前同步模式内存大小512-2048范围 在服务器配置情况下最大化内存 输入以下命令 geth --fast --cache=2048 最快同步模式也是 保 ...

  10. java类与对象(属性,方法)的使用

    ---恢复内容开始--- 类和对象是java编程中很重要的应该面向对象的一课,实际上可以将类看作对象的载体,它定义了对象所具有的功能.Java是面向对象的语言,因此掌握类与对象是学习Java语言的基础 ...