Return the text words as a list with the bbox for each word. Args: page: pymupdf.Page clip: (rect-like) area on page to consider flags: (int) control the amount of data parsed into the textpage. textpage: (pymupdf.TextPage) either passed-in or None. sort:
(
page: pymupdf.Page,
clip: rect_like = None,
flags: OptInt = None,
textpage: pymupdf.TextPage = None,
sort: bool = False,
delimiters=None,
tolerance=3,
)
| 84 | |
| 85 | |
| 86 | def get_text_words( |
| 87 | page: pymupdf.Page, |
| 88 | clip: rect_like = None, |
| 89 | flags: OptInt = None, |
| 90 | textpage: pymupdf.TextPage = None, |
| 91 | sort: bool = False, |
| 92 | delimiters=None, |
| 93 | tolerance=3, |
| 94 | ) -> list: |
| 95 | """Return the text words as a list with the bbox for each word. |
| 96 | |
| 97 | Args: |
| 98 | page: pymupdf.Page |
| 99 | clip: (rect-like) area on page to consider |
| 100 | flags: (int) control the amount of data parsed into the textpage. |
| 101 | textpage: (pymupdf.TextPage) either passed-in or None. |
| 102 | sort: (bool) sort the words in reading sequence. |
| 103 | delimiters: (str,list) characters to use as word delimiters. |
| 104 | tolerance: (float) consider words to be part of the same line if |
| 105 | top or bottom coordinate are not larger than this. Relevant |
| 106 | only if sort=True. |
| 107 | |
| 108 | Returns: |
| 109 | Word tuples (x0, y0, x1, y1, "word", bno, lno, wno). |
| 110 | """ |
| 111 | |
| 112 | def sort_words(words): |
| 113 | """Sort words line-wise, forgiving small deviations.""" |
| 114 | words.sort(key=lambda w: (w[3], w[0])) |
| 115 | nwords = [] # final word list |
| 116 | line = [words[0]] # collects words roughly in same line |
| 117 | lrect = pymupdf.Rect(words[0][:4]) # start the line rectangle |
| 118 | for w in words[1:]: |
| 119 | wrect = pymupdf.Rect(w[:4]) |
| 120 | if ( |
| 121 | abs(wrect.y0 - lrect.y0) <= tolerance |
| 122 | or abs(wrect.y1 - lrect.y1) <= tolerance |
| 123 | ): |
| 124 | line.append(w) |
| 125 | lrect |= wrect |
| 126 | else: |
| 127 | line.sort(key=lambda w: w[0]) # sort words in line l-t-r |
| 128 | nwords.extend(line) # append to final words list |
| 129 | line = [w] # start next line |
| 130 | lrect = wrect # start next line rect |
| 131 | |
| 132 | line.sort(key=lambda w: w[0]) # sort words in line l-t-r |
| 133 | nwords.extend(line) # append to final words list |
| 134 | |
| 135 | return nwords |
| 136 | |
| 137 | pymupdf.CheckParent(page) |
| 138 | if flags is None: |
| 139 | flags = pymupdf.TEXTFLAGS_WORDS |
| 140 | tp = textpage |
| 141 | if tp is None: |
| 142 | tp = page.get_textpage(clip=clip, flags=flags) |
| 143 | elif getattr(tp, "parent") != page: |
no test coverage detected
searching dependent graphs…