Python处理文档

Python处理文档

Python可以创建和修改具有.docx文件的Word文档扩展,使用python-docx模块。您可以运行命令 sudo pip3 install python-docx 进行安装。

注意
使用pip首次安装 Python-Docx 时,请确保安装 python-docx ,而不是 docx 。安装名称 docx 适用于本书未涵盖的其他模块。但是,当您要导入 python-docx 模块时,您需要运行导入docx,而不是导入python-docx。

如果你没有Word,那么LibreOffice Writer和OpenOffice Writer都是Windows,OS X和Linux的免费替代应用程序都可以用于打开.docx文件。您可以从libreofficeopenoffice下载它们。 Python的完整文档 - Docx可在python-docx获得。虽然有一个Word for OS X的版本,本章将重点介绍Word for Windows。

与明文相比,.docx文件有很多结构。这种结构在Python-Docx中由三种不同的数据类型表示。最高的
层级,Document对象代表整个文档。 Document对象包含文档中段落的 Paragraph objects 列表。 (一个每当用户按下 ENTER 或 RETURN 时,Word文档中就会产生新段落。)这些 Paragraph objects 中的每一个都包含一个或多个 Run 对象的列表。图13-4中的单句段落有四个 runs。
图13-4

图中的文本在Word文档中不仅仅是一个字符串。它有字体(Font),大小(size),颜色(color)以及与之相关的其他样式信息。 Word 中的 style 是这些属性的集合。 Run 对象是一个连续的文本运行相同的 style。每当文本的 style 更改时,都需要新的Run对象。

读取Word文本

#! /usr/bin/python3
import docx
doc = docx.Document('demo.docx')  # point 1
print(str(len(doc.paragraphs)))   # point 2
print(doc.paragraphs[0].text)     # point  3 
print(doc.paragraphs[1].text)     # point  4
print(str(len(doc.paragraphs[1].runs)))  # point  5

for runIndex in range(len(doc.paragraphs[1].runs)):
    print(doc.paragraphs[1].runs[runIndex].text)


# 输出内容是
7
Document Title
A plain paragraph with some bold and some italic
5
A plain paragraph with
 some 
bold
 and some 
italic

在 point 1. 在Python里面打开一个 .docx 文件,把文件名 demo.docx 传给 docx.Document() 函数。它将会返回一个 Document object. 这个对象有一个 paragraphs 属性。 这个属性是含有 Paragraph objects 的列表对象。这些段落对象中的每一个都有一个 text 属性,该属性包含该段落中文本的字符串(不含风格信息)。这里,第一个文本属性包含’DocumentTitle’,第二个包含’A plain paragraph with some bold and some italic’。

每个Paragraph object 还有一个 runs 属性,它是 Run objects 组成的 List。Run object 也有一个 text属性,只包含这个Paragraph objects 的 Run objects 的文本。让我们看看第二段中的文本属性对象,‘A plain paragraph with some bold and some italic’。对 Paragraph object 调用len(),结果告诉我们有四个Run对象。第一次运行对象包含’A plain paragraph with some’。然后,文本样式变成了粗体,所以 ‘bold’ 启动一个新的 Run object。之后文本又变成了没有加粗的普通样式,这导致第三个Run object,‘and some’。最后一个 Run objects 包含一个斜体样式的’italic’。
使用Python-Docx,您的Python程序现在可以读取来自.docx文件的文本,并像使用任何其他字符串值一样使用它。

从 .docx 文件中获取所有文本

如果你值关心文本信息,不关心样式信息,在 word 文档中,你可以使用 getText() 功能。 它接收文本名作为参数,然后返回这个 word document 的所有文本信息。

#! /usr/bin/python3

import docx

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

getText() 函数打开Word文档,循环遍历列表中的所有 paragraph object,然后将其文本附加到 List 变量 fullText 中。循环之后,fullText中的字符串以换行符连接在一起。
readDocx.py程序可以像任何其他模块一样导入。现在,如果您只需要Word文档中的文本,则可以输
以下:

>>> import readDocx
>>> print(readDocx.getText('demo.docx'))
Document Title
A plain paragraph with some bold and some italic
Heading, level 1
Intense quote
first item in unordered list
first item in ordered list

您还可以调整 getText() 以在返回之前修改字符串它。例如,要缩进每个段落,请替换 append() 调用
readDocx.py用这个:

fullText.append('  ' + para.text)

要在段落之间添加双空格,请更改 join() 调用
代码:

return '\n\n'.join(fullText)

如您所见,编写函数只需几行代码将读取.docx文件,并根据您的喜好返回其内容的字符串。

给 Paragraph 和 Run objects 添加样式

在Word for Windows中,您可以通过按 ctrl-alt-shift-S 来查看样式,显示“样式”窗格,如图13-5所示。
图13-5

Word和其他文字处理器使用样式来保持视觉呈现相似类型的文本一致且易于更改。例如,也许你想在11点设置身体段落,Times New Roman,左对齐,粗糙的右文。您可以使用这些设置创建样式并将其指定给所有正文段落。那么,如果你以后想要改变前期在文件中发送所有正文段落,你只需改变样式即可,所有这些段落将自动更新。

对于Word文档,有三种类型的样式:Paragraph 可以应用于 Paragraph objects,character styles 可以应用于 Run objects,linked styles 可以应用于这两种对象。你可以给 Paragraph 和 Run 对象设置样式,方法是将其 style 属性设置为特定的字符串。该字符串是样式的名称。如果style设置为None,那么将不会有样式关联到 Paragraph 或 Run 对象。

默认Word样式的字符串值如下:

  • ‘Normal’
  • ‘BodyText’ ‘BodyText2’ ‘BodyText3’
  • ‘Caption’
  • ‘Heading1’ ‘Heading2’ ‘Heading3’ ‘Heading4’ ‘Heading5’ ‘Heading6’ ‘Heading7’ ‘Heading8’ ‘Heading9’
  • ‘IntenseQuote’
  • ‘List’ ‘List2’ ‘List3’ ‘ListBullet’ ‘ListBullet2’ ‘ListBullet3’
  • ‘ListContinue’ ‘ListContinue2’ ‘ListContinue3’
  • ‘ListNumber’ ‘ListNumber2’ ‘ListNumber3’
  • ‘ListParagraph’
  • ‘MacroText’
  • ‘NoSpacing’
  • ‘Quote’
  • ‘Subtitle’
  • ‘TOCHeading’
  • ‘Title’
    设置 Style 属性时,请勿在样式名称中使用空格。例如,虽然样式名称可能是 Subtle 和 Emphasis,但您应该设置 style 属性为字符串值 ‘SubtleEmphasis’ 而不是 ‘Subtle Emphasis’。
    包含空格将导致 Word 误读样式名称而不应用它。
    对 Run object 使用链接样式时,需要添加 “Char” 到它的名字的末尾。例如,为 一个 paragraph object 设置 Quote 链接样式,你会使用 paragraphObj.style =‘Quote’,但是对于 Run object ,你会使用 runObj.style =‘QuoteChar’。
    在当前版本的Python-Docx(0.7.4)中,唯一可以使用的样式是: 默认的Word使用的样式和 .docx 文档中使用的样式。无法创建新的样式 - 虽然这可能会在以后的版本中更改 Python 的 DOCX。

使用非默认样式创建Word文档

如果要创建使用一些超出默认值的样式的Word文档,你需要打开Word到一个空白的Word文档并创建。通过单击样式底部的“新建样式”按钮来设置自己的样式窗格(图13-6在Windows上显示)。这将打开“从格式创建新样式”对话框可以进入新的风格。然后,返回交互式shell并打开这个空白的Word文档与docx.Document(),使用它作为您的基础Word文档。您现在可以使用此样式的名称使用Python-Docx。
图13-6

Run Attributes

可以使用文本属性进一步设置运行样式。可以设置每个属性三个值之一:True(无论如何,该属性始终启用其他样式应用于运行),False(该属性始终被禁用),或者 None(默认为运行样式设置的任何内容)。
表13-1列出了可以在Run对象上设置的文本属性。

属性 描述
bold The text appears in bold.
italic The text appears in italic.
underline The text is underlined.
strike The text appears with strikethrough.
double_strike The text appears with double strikethrough.
all_caps The text appears in capital letters.
small_caps The text appears in capital letters, with
lowercase letters two points smaller.
shadow The text appears with a shadow.
outline The text appears outlined rather than solid.
rtl The text is written right-to-left.
imprint The text appears pressed into the page.
emboss The text appears raised off the page in relief.

例如,要更改demo.docx的样式,请输入以下内容交互式shell:

huxing@huxing:~/my-repo/PythonLearn$ python
Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import docx
>>> doc = docx.Document('demo.docx')
>>> doc.paragraphs[0].text
'Document Title'
>>> doc.paragraphs[0].style
_ParagraphStyle('Title') id: 140382848736560
>>> doc.paragraphs[0].stype = 'Normal'
>>> doc.paragraphs[0].style = 'Normal'
>>> doc.paragraphs[0].style
_ParagraphStyle('Normal') id: 140382855567232
>>> doc.paragraphs[1].text
'A plain paragraph with some bold and some italic'
>>> (doc.paragraphs[1].runs[0].text, doc.paragraphs[1].runs[1].text, doc.paragraphs[1].runs[2].text, doc.paragraphs[1].runs[3].text)
('A plain paragraph with', ' some ', 'bold', ' and some ')
>>> doc.paragraphs[1].runs[0].style = 'QuoteChar'
>>> doc.paragraphs[1].runs[1].underline = True
>>> doc.paragraphs[1].runs[3].underline = True
>>> doc.save('restyled.docx')

在这里,我们使用 text 和 style 属性轻松查看其中的内容我们的文件中的段落。 将一个 paragraph 划分成多个 runs , 然后单独访问每一个 run object 。所以我们在第二个 paragraph 中得到第一个,第二个,第四个 run,给每个run object 设置不同的 style,并保存结果到一个新文件。

restyled.docx 顶部的文字标题将具有 Normal style 而不是 Title style,Run object 为文本 A plain
paragraph 有一些将具有 QuoteChar style,以及两个 Run object对于 bold 和 italic,将下划线属性设置为True。
图13-7显示了如何在restyled.docx中查看段落和运行的样式。
图13-7
您可以在这里找到有关Python-Docx使用的更完整的文档样式。

Writing Word Documents

#! /usr/bin/python3

import docx
doc = docx.Document()
doc.add_paragraph('Hello world!')
doc.add_paragraph('This is my first world document file.')
doc.save('helloworld.docx')

要创建自己的.docx文件,请调用 docx.Document() 以返回一个新的空白Word文档对象。 add_paragraph() 文档方法添加了一个新的文本段落到文档并返回对段落的引用已添加的对象。完成文本添加后,传递文件名字符串给 save() 方法, 将 Document 对象保存到文件中。
这将在当前工作中创建一个名为helloworld.docx的文件:
图13-8
您可以通过再次调用 add_paragraph() 方法添加段落用新段落的文字。或者将文本添加到现有参数的末尾,您可以调用段落的 add_run() 方法并将其传递给字符串。
在交互式shell中输入以下内容:

#! /usr/bin/python3

import docx
doc = docx.Document()
doc.add_paragraph('Hello world!')
doc.add_paragraph('This is my first world document file.')

paraObj1 = doc.add_paragraph('If you want to see more, please add me by Wechat: fishing_late.')
paraObj2 = doc.add_paragraph('This work is translate from one interesting book.')
paraObj1.add_run('Or anything else if you want to tell me. feel free!.')

doc.save('helloworld.docx')

请记住,从Python-Docx版本0.5.3开始,新的 Paragraph object 只能添加到文档的末尾,并且新的 Run object 仅能添加到 Paragraph object 的末尾。可以再次调用 save() 方法覆盖你已经保存的内容。
图13-9

add_paragraph() 和add_run() 都接受可选的第二个参数, 这是 Paragraph 或 Run object 样式的字符串。例如:

>>> doc.add_paragraph('Hello world!', 'Title')

这一行添加了一个带有Title 样式的文本Hello world到段落中!

Adding Headings

调用 add_heading() 会添加一个带有其中一个标题样式的段落。输入以下进入交互式shell:

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import docx
>>> doc =docx.Document()
>>> doc.add_heading('Header 0', 0)
<docx.text.paragraph.Paragraph object at 0x7f530ad24048>
>>> doc.add_heading('Header 1', 1)
<docx.text.paragraph.Paragraph object at 0x7f530ace45c0>
>>> doc.add_heading('Header 2', 2)
<docx.text.paragraph.Paragraph object at 0x7f531092d588>
>>> doc.add_heading('Header 3', 3)
<docx.text.paragraph.Paragraph object at 0x7f530ad24048>
>>> doc.add_heading('Header 4', 4)
<docx.text.paragraph.Paragraph object at 0x7f530ace45c0>
>>> doc.save('headings.docx')
>>> quit()

add_heading() 的参数是标题文本的字符串0到4之间的整数。整数0使标题成为Title样式,
用于文档顶部。整数1到4用于各种航向水平,1为主航向,4为最低航向。add_heading() 函数返回一个Paragraph对象以保存步骤。从Document对象中提取它作为一个单独的步骤。
图13-10

添加换行和换页

要添加换行符(而不是开始一个全新的段落),您可以在要运行中断的Run对象上调用add_break()方法。如果您想要添加分页符,则需要将docx.text.WD_BREAK.PAGE作为值传递给 add_break()的唯一参数:

>>> import docx
>>> doc = docx.Document()
>>> doc.add_paragraph('This is on the first page!')
<docx.text.paragraph.Paragraph object at 0x7feb18c47550>
>>> doc.paragraphs[0].runs[0].add_break(docx.enum.WD_BREAK.PAGE)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'docx.enum' has no attribute 'WD_BREAK'
>>> doc.paragraphs[0].runs[0].add_break(docx.enum.text.WD_BREAK.PAGE)
>>> doc.add_paragraph('This is on the second page!')
<docx.text.paragraph.Paragraph object at 0x7feb18c475f8>
>>> doc.save('twoPage.docx')
>>> exit()

这将创建一个两页的Word文档,This is on the first page! 在第一页上,This is on the second page! 在第二个。 即使文本后面的第一页上仍然有足够的空间!,我们通过插入分页符强制开始新页面.

添加图片

Document objects 有一个add_picture()方法,可以让你添加一个图像到文档的末尾。 假设你当前的工作目录有一个文件 zophie.png。 您可以将 zophie.png 添加到文档的末尾 - 宽度为1英寸,高度为4厘米(Word可以使用输入以下内容:英制和公制单位):

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import docx
>>> doc = docx.Document()
>>> doc.add_picture('hack_pg.png', width=docx.shared.Inches(1), height=docx.shared.Cm(4))
<docx.shape.InlineShape object at 0x7ffb93552dd8>
>>> doc.save('pictureDoc.docx')
>>> quit()

第一个参数是图像文件名的字符串。 可选的width和height关键字参数将设置的宽度和高度
文档中的图像。 如果省略,宽度和高度将默认为图像的正常大小。你可能更喜欢用熟悉的方式指定图像的高度和宽度单位,如英寸和厘米,所以你可以使用 docx.shared.Inches() 和 docx.shared.Cm()函数在指定宽度和高度时起作用关键字参数。

猜你喜欢

转载自blog.csdn.net/fudaxing/article/details/88736916