前言:Python读取word文本时,报错‘UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\u2002’ in position 0: illegal multibyte sequence’。处理报错后word文本可以正常打印。
吐槽一下csdn,找了半天没有一个可以正确处理的办法,大多数文章总是大同小异没有原创的,生气。
参考博文:https://www.cnblogs.com/1blog/p/15186566.html
源代码
file = Document('.\\测试.docx')
for i in file.paragraphs:
for run in i.runs:
print(run.text)
报错如下:
Traceback (most recent call last):
File "D:/PycharmProjects/fracturing/test.py", line 15, in <module>
print(run.text)
UnicodeEncodeError: 'gbk' codec can't encode character '\u2002' in position 0: illegal multibyte sequence
‘\u2002’是以反斜杠u(\u)开头的16进制Unicode编码,这些特殊字符通常不在ASCII可见字符范围内,因此我们在查看word或浏览网页时看不到这些字符,但是在分析word文件以及网页源码时会遇到。
类似的还有
\n 回车(\u000a)
\t 水平制表符(\u0009)
\s 空格(\u0008)(全角半角就不区分了)
\r 换行(\u000d)
\u200b \xa0 \u3000等
使用split方法
file = Document('.\\text.docx')
for i in file.paragraphs:
for run in i.runs:
a = run.text
print(''.join(a.split()))
或
file = Document('.\\text.docx')
for i in file.paragraphs:
for run in i.runs:
print(''.join(run.text.split()))