Python - Document Word de processus

Pour lire un document Word, nous prenons l'aide du module nommé docx. Nous installons d'abord docx comme indiqué ci-dessous. Ensuite, écrivez un programme pour utiliser les différentes fonctions du module docx pour lire le fichier entier par paragraphes.

Nous utilisons la commande ci-dessous pour obtenir le module docx dans notre environnement.

pip install docx

Dans l'exemple ci-dessous, nous lisons le contenu d'un document Word en ajoutant chacune des lignes à un paragraphe et enfin en imprimant tout le texte du paragraphe.

import docx
def readtxt(filename):
    doc = docx.Document(filename)
    fullText = []
    for para in doc.paragraphs:
        fullText.append(para.text)
    return '\n'.join(fullText)
print (readtxt('path\Tutorialspoint.docx'))

Lorsque nous exécutons le programme ci-dessus, nous obtenons la sortie suivante -

Tutorials Point originated from the idea that there exists a class of readers who respond 
better to online content and prefer to learn new skills at their own pace from the comforts 
of their drawing rooms. 
The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, 
we worked our way to adding fresh tutorials to our repository which now proudly flaunts 
a wealth of tutorials and allied articles on topics ranging from programming languages 
to web designing to academics and much more.

Lecture de paragraphes individuels

Nous pouvons lire un paragraphe spécifique du document Word en utilisant l'attribut paragraphes. Dans l'exemple ci-dessous, nous lisons uniquement le deuxième paragraphe du document Word.

import docx
doc = docx.Document('path\Tutorialspoint.docx')
print len(doc.paragraphs)
print doc.paragraphs[2].text

Lorsque nous exécutons le programme ci-dessus, nous obtenons la sortie suivante -

The journey commenced with a single tutorial on HTML in 2006 and elated by the response 
it generated, we worked our way to adding fresh tutorials to our repository 
which now proudly flaunts a wealth of tutorials and allied articles on topics 
ranging from programming languages to web designing to academics and much more.