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

UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘u2002‘ in position 28: illegal......,第1张

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

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5658168.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存