是否可以使用python从pdf中提取特定的文本。
测试用例:我有一个超过10页的PDF文件,我需要提取特定的文本和与它们相关联的值。示例:用户:value用户id:value。需要提取这些值。
我能够阅读所有的页面,我现在想要具体的文本。
发布于 2020-05-10 10:35:45
如果您已经能够读取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‘的字符,直到它不能再匹配“+”为止。
如果您只想要返回"value“字段,则可以使用:r‘’user:\s(\w+)‘来指示regex引擎将匹配的字符串分组为'\w+’。如果regex模式中有组,findall将返回组匹配的列表,因此结果如下:
results = re.findall(r'user:\s(\w+)', pdf_text)
['John', 'Doe']查看regex模块文档,请访问:https://docs.python.org/3/library/re.html
其他一些方法,如finditer(),也可以帮助您处理更复杂的事情。
这个regex指南也可能有帮助:https://www.regexbuddy.com/regex.html?wlr=1
https://stackoverflow.com/questions/61710068
复制相似问题