使用python将pdf转word
时间: 2023-09-06 07:10:12 浏览: 54
你可以使用Python中的第三方库PyPDF2将PDF文件转换为文本文件,然后使用Python中的第三方库python-docx将文本文件转换为Word文件。以下是一个例子:
```python
import os
import PyPDF2
from docx import Document
def pdf_to_text(pdf_path):
with open(pdf_path, 'rb') as pdf_file:
read_pdf = PyPDF2.PdfFileReader(pdf_file)
text = ''
for page in range(read_pdf.getNumPages()):
text += read_pdf.getPage(page).extractText()
return text
def text_to_word(text_path, word_path):
document = Document()
with open(text_path, 'r') as text_file:
for line in text_file:
document.add_paragraph(line.strip())
document.save(word_path)
if __name__ == '__main__':
pdf_path = '/path/to/pdf'
text_path = '/path/to/text'
word_path = '/path/to/word'
text = pdf_to_text(pdf_path)
with open(text_path, 'w') as text_file:
text_file.write(text)
text_to_word(text_path, word_path)
os.remove(text_path) # 删除中间生成的文本文件
```
在代码中,`pdf_to_text`函数使用PyPDF2库将PDF文件转换为纯文本。`text_to_word`函数使用python-docx库将纯文本转换为Word文件。最后,使用`os.remove`函数删除中间生成的文本文件。