Учебники

Python — обработка документов Word

Чтобы прочитать документ Word, мы воспользуемся помощью модуля с именем docx. Сначала мы устанавливаем DOCX, как показано ниже. Затем напишите программу для использования различных функций в модуле docx, чтобы прочитать весь файл по абзацам.

Мы используем команду ниже, чтобы вставить модуль docx в нашу среду.

 pip install docx 

В приведенном ниже примере мы читаем содержимое текстового документа, добавляя каждую строку к абзацу и, наконец, распечатывая весь текст абзаца.

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'))

Когда мы запускаем вышеуказанную программу, мы получаем следующий вывод:

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.

Чтение отдельных параграфов

Мы можем прочитать определенный абзац из документа word, используя атрибут абзаца. В приведенном ниже примере мы читаем только второй абзац из слова document.

import docx

doc = docx.Document('path\Tutorialspoint.docx')
print len(doc.paragraphs)

print doc.paragraphs[2].text

Когда мы запускаем вышеуказанную программу, мы получаем следующий вывод: