我拥有的.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
由于您在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.