我编写了以下代码,将docx文件转换为文本文件。我在文本文件中打印的输出是整个文件的最后一个段落/部分,而不是完整的内容。代码如下:
from docx import Document
import io
import shutil
def convertDocxToText(path):
for d in os.listdir(path):
fileExtension=d.split(".")[-1]
if fileExtension =="docx":
docxFilename = path + d
print(docxFilename)
document = Document(docxFilename)
# for printing the complete document
print('\nThe whole content of the document:->>>\n')
for para in document.paragraphs:
textFilename = path + d.split(".")[0] + ".txt"
with io.open(textFilename,"w", encoding="utf-8") as textFile:
#textFile.write(unicode(para.text))
x=unicode(para.text)
print(x) //the complete content gets printed by this line
textFile.write((x)) #after writing the content to text file only last paragraph is copied.
#textFile.write(para.text)
path= "/home/python/resumes/"
convertDocxToText(path)
答案 0 :(得分:1)
如您的代码在上一个for
循环中所述:
for para in document.paragraphs:
textFilename = path + d.split(".")[0] + ".txt"
with io.open(textFilename,"w", encoding="utf-8") as textFile:
x=unicode(para.text)
textFile.write((x))
对于整个文档中的每个段落,您尝试打开一个名为textFilename
的文件,因此假设您在MyFile.docx
中有一个名为/home/python/resumes/
的文件,因此textFilename
的值包含的路径在整个/home/python/resumes/MyFile.txt
循环中将始终是for
,因此问题在于您以w
模式(即Write
模式)打开了同一文件,并且覆盖整个文件内容。
您必须从for循环中打开一次文件,然后尝试将文件逐段添加。
答案 1 :(得分:0)
以下是上述问题的解决方案:
from docx import Document
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,"w", encoding="utf-8") as textFile:
for para in document.paragraphs:
textFile.write(unicode(para.text))
path= "/home/python/resumes/"
convertDocxToText(path)