簡體   English   中英

使用 python 從 pdf 中提取特定文本

[英]extraction of specific text from pdf using python

是否可以使用 python 從 pdf 中提取特定文本。

測試用例:我有一個10多頁的PDF文件,我需要提取出具體的文本和與之關聯的值。 示例:用戶:值用戶 ID:值 需要提取這些值。

我能夠閱讀所有頁面,我現在想要特定的文本

如果您已經能夠閱讀 PDF 並將文本存儲到字符串中,則可以執行以下操作:

import re # Import the Regex Module

pdf_text = """
user:John
user:Doe
user id:2
user id:4
"""

# re.findall will create a list of all strings matching the specified pattern
results = re.findall(r'user:\s\w+', pdf_text)
results = ['user: John', 'user: Doe']

這基本上意味着:查找所有以字符串 'user:' 開頭的匹配項,后跟一個空格 '\s',然后是組成單詞(字母和數字)的字符 '\w',直到它不再匹配 '+' .

如果您只想取回“值”字段,則可以使用:r'user:\s(\w+)',它會指示正則表達式引擎對與 '\w+' 匹配的字符串進行分組。 如果您的正則表達式模式中有組,則 findall 返回一個組匹配列表,因此結果將是:

results = re.findall(r'user:\s(\w+)', pdf_text)
['John', 'Doe']

查看正則表達式模塊文檔: https://docs.python.org/3/library/re.html

如果您想做更復雜的事情,其他一些方法,如 finditer() 也可以提供幫助。

此正則表達式指南也可能有所幫助: https://www.regexbuddy.com/regex.html?wlr=1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM