栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

2021-10-25

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-10-25

解决python文本读取编码不匹配问题

无论是文本读取还是语料库载入都会遇到编码不匹配问题,这是因为python默认的编码模式和文本编码模式不匹配造成。
网上的方法很多,我这里介绍一种最简单的方法。以我遇到的错误情况为例。

载入语料库发生错误

from nltk.corpus import BracketParseCorpusReader

corpus_root = "E:\nlp_test1"
file_pattern = '.*'
ptb = BracketParseCorpusReader(corpus_root, file_pattern)
ptb.fileids()
ptb.raw("199801.txt")

但由于199801.txt编码方式为GB3212,运行出现错误提示为:

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

这里我们只需要把txt文档变成utf-8的编码格式即可。不需要写复杂的格式转换代码,只需要找一份编码格式为utf-8的文档,复制199801的内容到新文件里面,就完成了格式转换,新格式的文件命名为1998.txt

from nltk.corpus import BracketParseCorpusReader

corpus_root = "E:\nlp_test1"
file_pattern = '.*'
ptb = BracketParseCorpusReader(corpus_root, file_pattern)
ptb.fileids()
ptb.raw("1998.txt")

运行即可成功。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/350834.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号