如何使用Python中的表格从.docx中提取文本

问题描述 投票:0回答:1

我拥有的.docx文件具有表,标题等,我想知道如何从该文档中提取文本。我能找到的唯一示例代码使用段落,并且不适用于我的文件。

这里是代码:

    doc = docx.Document(self.filename)
    fullText = []
    for para in doc.paragraphs:
        txt = para.text.encode('ascii', 'ignore')
        fullText.append(txt)
    self.text = '\n'.join(fullText)

当我运行此代码时,出现此错误:

 File "annotatorConnections.py", line 75, in openFile
    self.text = '\n'.join(fullText)
TypeError: sequence item 0: expected str instance, bytes found
python python-3.x docx
1个回答
0
投票

由于您在fullText中获取的是字节类型而不是字符串类型,因此可以使用它来使之正常工作:

doc = docx.Document(self.filename)
fullText = []
for para in doc.paragraphs:
    txt = para.text.encode('ascii', 'ignore')
    fullText.append(txt)
self.text = b'\n'.join(fullText)             ---------> Add prefix b to make it a byte object.
© www.soinside.com 2019 - 2024. All rights reserved.