-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathparagraph.py
More file actions
87 lines (68 loc) · 3.03 KB
/
paragraph.py
File metadata and controls
87 lines (68 loc) · 3.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from typing import Any, List
from python_docx_replace.block_handler import BlockHandler
from python_docx_replace.key_changer import KeyChanger
class Paragraph:
@staticmethod
def get_all(doc) -> List[Any]:
paragraphs = list()
paragraphs.extend(Paragraph._get_paragraphs(doc))
for section in doc.sections:
paragraphs.extend(Paragraph._get_paragraphs(section.header))
paragraphs.extend(Paragraph._get_paragraphs(section.footer))
return paragraphs
@staticmethod
def _get_paragraphs(item: Any) -> Any:
yield from item.paragraphs
# get paragraphs from tables
for table in item.tables:
for row in table.rows:
for cell in row.cells:
for paragraph in cell.paragraphs:
yield paragraph
def __init__(self, p) -> None:
self.p = p
def delete(self) -> None:
paragraph = self.p._element
paragraph.getparent().remove(paragraph)
paragraph._p = paragraph._element = None
def contains(self, key) -> bool:
return key in self.p.text
def startswith(self, key) -> bool:
return str(self.p.text).strip().startswith(key)
def endswith(self, key) -> bool:
return str(self.p.text).strip().endswith(key)
def replace_key(self, key, value) -> None:
if key in self.p.text:
self._simple_replace_key(key, value)
if key in self.p.text:
self._complex_replace_key(key, value)
self._replace_hyperlinks(key, value)
def replace_block(self, initial, end, keep_block) -> None:
block_handler = BlockHandler(self.p)
block_handler.replace(initial, end, keep_block)
def clear_tag_and_before(self, key, keep_block) -> None:
block_handler = BlockHandler(self.p)
block_handler.clear_key_and_before(key, keep_block)
def clear_tag_and_after(self, key, keep_block) -> None:
block_handler = BlockHandler(self.p)
block_handler.clear_key_and_after(key, keep_block)
def _simple_replace_key(self, key, value) -> None:
# try to replace a key in the paragraph runs, simpler alternative
for run in self.p.runs:
if key in run.text:
run.text = run.text.replace(key, value)
def _complex_replace_key(self, key, value) -> None:
# complex alternative, which check all broken items inside the runs
while key in self.p.text:
# if the key appears more than once in the paragraph, it will replaced all
key_changer = KeyChanger(self.p, key, value)
key_changer.replace()
def _replace_hyperlinks(self, key, value) -> None:
# Make replacements in hyperlink texts
for link in self.p._element.xpath(".//w:hyperlink"):
try:
inner_run = link.xpath("w:r", namespaces=link.nsmap)[0]
except IndexError:
continue
if key in inner_run.text:
inner_run.text = inner_run.text.replace(key, value)