python - 如何从各种pdf列表中提取关键字
问题描述
我在 python 中有一个包含很多 url 的列表,我做了一个循环来下载所有在 mi 桌面的地毯上。到目前为止,每一个pdf都有这样的名字:document0,document1,.....,documentx
我想做的是从每个 pdf 文件中提取关键字,但到目前为止,我一直无法弄清楚如何做到这一点。
"""
Created on Tue Aug 17 11:03:34 2019
@author: xxxx
"""
#This code is for only one of the pdf but I want do it for each one with
#the characteristics described above.
import os
os.chdir("//DOCUMENTS/")
import PyPDF2
import re
object = PyPDF2.PdfFileReader("document3.pdf")
NumPages=object.getNumPages()
String="USD"
for i in range(1, NumPages):
PageObj = object.getPage(i)
print("this is page " + str(i))
Text = PageObj.extractText()
# print(Text)
ResSearch = re.search(String, Text)
print(ResSearch)
解决方案
进行 shell 样式名称匹配的一种快速方法是使用该glob
模块。下面,我重写了您的代码以从 pdf 文件返回匹配的生成器。然后,我们将所有文档的所有此类匹配的计数加在一起。
import os
from glob import glob
import re
from PyPDF2 import PdfFileReader
def search_page(pattern, page):
yield from pattern.findall(page.extractText())
def search_document(pattern, path):
document = PdfFileReader(path)
for page in document.pages:
yield from search_page(pattern, page)
pattern = re.compile(r'USD') # Or r'\bUSD\b' if you don't want to match words containing USD
count = 0
for path in glob('//DOCUMENTS/document*.pdf'):
matches = search_document(pattern, path)
count += sum(1 for _ in matches)
print(f"Total count is {count}") # "Total count is {}".format(count)
推荐阅读
- haskell - Haskell 中更整洁的二进制文件处理
- powershell - 如何在 PowerShell 中创建私有类成员?
- java - 如何将这段 C# 泛型翻译成 Java
- windows - 如何在 Visual Studio 中将资源管理器作为预构建事件重新启动
- swift - 我正在尝试制作一张在快速滑动时滑动的卡片
- ruby-on-rails - Rails:从 github 下载后,Bundle Install 无法安装必要的 gem
- c# - 尽管共享相同的选定项属性,但从列表框中选择新项不会从另一个列表框中取消选择现有选定项
- php - 如何让服务像 SwiftMailer 一样在 kernel.terminate 上工作?
- sql - oracle join 创建重复记录
- c# - 如何将我从数据库中获得的实体绑定到我的请求的 DTO?