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

UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘u2002‘ in position 28: illegal......

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

UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘u2002‘ in position 28: illegal......

UnicodeEncodeError: 'gbk' codec can't encode character 'u2002' in position 28: illegal multibyte sequence

import pdfplumber
path = 'D:毕设(企业数字化转型)政治基因/政治关联、企业并购特征与并购绩效_张雯.pdf'
pdf = pdfplumber.open(path)

def txt_create(msg):
    file = open('./政治关联、企业并购特征与并购绩效_张雯.txt', 'a')
    file.write(msg)
    file.close()

for page in pdf.pages:
    txt_create(page.extract_text())

但是如果不写入txt,只是print的话就没事

import pdfplumber
path = 'D:毕设(企业数字化转型)政治基因/政治关联、企业并购特征与并购绩效_张雯.pdf'
pdf = pdfplumber.open(path)

def txt_create(msg):
    file = open('./政治关联、企业并购特征与并购绩效_张雯.txt', 'a')
    file.write(msg)
    file.close()

for page in pdf.pages:
    # txt_create(page.extract_text())
    print(page.extract_text())

 输出

 首先了解报错

错误大概意思是:Unicode编码错误:‘gbk’ 编码解码器(codec)不能编码Unicode字符‘u2002’......

回顾Unicode是什么(UTF-8 到底是什么意思?unicode编码简介)

https://zhuanlan.zhihu.com/p/137875615https://zhuanlan.zhihu.com/p/137875615https://zhuanlan.zhihu.com/p/137875615

 可是明明print好好的,怎么写入文件就出错了呀。

说明在于创建txt时有编码问题:windows下,新文件默认编码为gbk, 那么python就直接用gbk去解析pdf了,从而出错了。

def txt_create(msg):
    file = open('./政治关联、企业并购特征与并购绩效_张雯.txt', 'a', encoding='utf-8') 
    #用'a'否则会覆盖写入,加一个encoding
    file.write(msg)
    file.close()

问题解决了

我是看这篇文章懂的

https://blog.csdn.net/qq_38008452/article/details/80423436https://blog.csdn.net/qq_38008452/article/details/80423436

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

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

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