如何在 Python 中将 .docx 转换为 .txt [英] How to convert .docx to .txt in Python

查看:54
本文介绍了如何在 Python 中将 .docx 转换为 .txt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将大量 MS Word 文件转换为纯文本格式.我不知道如何在 Python 中做到这一点.我在网上找到了以下代码.我的路径是本地路径,所有文件名都类似于 cx-xxx(即 c1-000、c1-001、c2-000、c2-001 等):

I would like to convert a large batch of MS Word files into the plain text format. I have no idea how to do it in Python. I found the following code online. My path is local and all file names are like cx-xxx (i.e. c1-000, c1-001, c2-000, c2-001 etc.):

from docx import [name of file]
import io
import shutil
import os

def convertDocxToText(path):
for d in os.listdir(path):
    fileExtension=d.split(".")[-1]
    if fileExtension =="docx":
        docxFilename = path + d
        print(docxFilename)
        document = Document(docxFilename)
        textFilename = path + d.split(".")[0] + ".txt"
        with io.open(textFilename,"c", encoding="utf-8") as textFile:
            for para in document.paragraphs: 
                textFile.write(unicode(para.text))

path= "/home/python/resumes/"
convertDocxToText(path)

推荐答案

使用 pypandoc 将 docx 转换为 txt:

Convert docx to txt with pypandoc:

import pypandoc

# Example file:
docxFilename = 'somefile.docx'
output = pypandoc.convert_file(docxFilename, 'plain', outputfile="somefile.txt")
assert output == ""

在此处查看官方文档:

https://pypi.org/project/pypandoc/

这篇关于如何在 Python 中将 .docx 转换为 .txt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆