【问题标题】:How to extract text from a docx file and store in a text file如何从 docx 文件中提取文本并存储在文本文件中
【发布时间】:2019-01-17 09:45:53
【问题描述】:

我一直在尝试读取 .docx 文件并将其文本复制到 .txt 文件中

我开始编写这段脚本来实现上述结果。

if extension == 'docx' :

   document = Document(filepath)
      for para in document.paragraphs:
         with open("C:/Users/prasu/Desktop/PySumm-resource/CodeSamples/output.txt","w") as file:
            file.writelines(para.text)

发生的错误如下:

Traceback (most recent call last):
  File "input_script.py", line 27, in <module>
    file.writelines(para.text)
  File "C:\Python\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2265' in 
position 0: character maps to <undefined>

我尝试在 print() 的帮助下打印“para.text”,它可以工作。 现在,我想将“para.text”写入 .txt 文件。

【问题讨论】:

标签: python nlp python-unicode traceback


【解决方案1】:

您可以尝试使用codecs

根据您的错误消息,以下字符“≥”似乎引起了问题。使用编解码器以 utf-8 输出应该有望解决您的问题。

from docx import Document
import codecs
filepath = r"test.docx"
document = Document(filepath)
for para in document.paragraphs:
    with codecs.open('output.txt', 'a', "utf-8-sig") as o_file:
        o_file.write(para.text)
    o_file.close()

【讨论】:

    猜你喜欢
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多