马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 blackantt 于 2023-4-28 11:21 编辑 import typing
from borb.pdf import Document
from borb.pdf import PDF
from borb.toolkit import SimpleTextExtraction
def main():
# read the Document
doc: typing.Optional[Document] = None
l: SimpleTextExtraction = SimpleTextExtraction()
with open("whose-button-is-this.pdf", "rb") as in_file_handle:
doc = PDF.loads(in_file_handle, [l])
# check whether we have read a Document
assert doc is not None
# print the text on the first Page
print(l.get_text(), len(l.get_text()), type(l.get_text())) #<class 'dict'>
print(l.get_text()[3])
for i in range(0, len(l.get_text())): #加这2行就会出错
print('----------------page', i, l.get_text()[i]) #加这2行就会出错
if __name__ == "__main__":
main()
----------------page 0 Whose
button
is this?
James Woolley Paul Kennedy Louise Gale
----------------page 1 Whose button is this?
This book belongs to
Traceback (most recent call last):
File "bord抽取pdf里的text到列表1.py", line 29, in <module>
main()
File "bord抽取pdf里的text到列表1.py", line 23, in main
print('----------------page', i, l.get_text()[i])
KeyError: 2
在您的第一次尝试中,出现了一个`KeyError`异常,这意味着在您试图使用一个不存在的键访问字典时发生了错误。在这种情况下,您尝试访问第三页(页码为2),但是字典中没有这样的键。
为了遍历字典中的所有页,您可以使用以下代码:
# Iterate through the pages
for page, text in l.get_text().items():
print(f"Page {page}: {text}")
这将打印字典中每一页的页码和文本。请注意,字典中的键是字符串类型而不是整数类型,因此我们使用了 `.items()` 方法来同时迭代键和值。
如果您只想遍历所有文本,可以使用以下代码:
# Iterate through all text
for text in l.get_text().values():
print(text)
这将打印字典中所有页的文本。
|