mirror of
https://github.com/jsvine/pdfplumber.git
synced 2026-08-29 16:40:24 +08:00
Add utils.filter_objects(...) and Page.filter(...)
This commit is contained in:
+17
-1
@@ -180,10 +180,12 @@ class Page(Container):
|
||||
x_tolerance=x_tolerance,
|
||||
y_tolerance=y_tolerance)
|
||||
|
||||
|
||||
def crop(self, bbox, strict=False):
|
||||
return CroppedPage(self, bbox, strict=strict)
|
||||
|
||||
def filter(self, fn):
|
||||
return FilteredPage(self, fn)
|
||||
|
||||
class CroppedPage(Page):
|
||||
def __init__(self, parent_page, bbox, strict=False):
|
||||
self.parent_page = parent_page
|
||||
@@ -202,3 +204,17 @@ class CroppedPage(Page):
|
||||
self.bbox,
|
||||
**kwargs)
|
||||
return self._objects
|
||||
|
||||
class FilteredPage(Page):
|
||||
def __init__(self, parent_page, fn):
|
||||
self.parent_page = parent_page
|
||||
self.fn = fn
|
||||
|
||||
@property
|
||||
def objects(self):
|
||||
if hasattr(self, "_objects"): return self._objects
|
||||
self._objects = utils.filter_objects(
|
||||
self.parent_page.objects,
|
||||
self.fn
|
||||
)
|
||||
return self._objects
|
||||
|
||||
@@ -195,6 +195,16 @@ def find_gutters(chars, orientation, min_size=5):
|
||||
gutters = gutters + [ end_max + Decimal('0.001') ]
|
||||
return gutters
|
||||
|
||||
def filter_objects(objs, fn):
|
||||
if isinstance(objs, dict):
|
||||
return dict((k, filter_objects(v, fn))
|
||||
for k,v in objs.items())
|
||||
|
||||
initial_type = type(objs)
|
||||
objs = to_list(objs)
|
||||
filtered = filter(fn, objs)
|
||||
|
||||
return initial_type(filtered)
|
||||
|
||||
def point_inside_bbox(point, bbox):
|
||||
px, py = point
|
||||
|
||||
@@ -101,3 +101,14 @@ class Test(unittest.TestCase):
|
||||
month_chars = within_bbox(page.chars, (0, 35, self.PDF_WIDTH, 65))
|
||||
month_text = collate_chars(month_chars, x_tolerance=2)
|
||||
assert(month_text == "November - 2015")
|
||||
|
||||
def test_filter(self):
|
||||
page = self.pdf.pages[0]
|
||||
def test(obj):
|
||||
if obj["object_type"] == "char":
|
||||
if obj["size"] < 20:
|
||||
return False
|
||||
return True
|
||||
filtered = page.filter(test)
|
||||
text = filtered.extract_text(x_tolerance=2)
|
||||
assert(text == "NICS Firearm Background Checks\nNovember - 2015")
|
||||
|
||||
Reference in New Issue
Block a user