首页 > 解决方案 > 读取目录中的所有文件并输出其中包含某些正则表达式的文件

问题描述

我正在尝试读取目录中的所有文件并输出包含正则表达式的文件以及每个文件中的正则表达式。

 import glob
import re
import PyPDF2
#-------------------------------------------------Input----------------------------------------------------------------------------------------------
folder_path = "/home/"
file_pattern = "/*"
folder_contents = glob.glob(folder_path + file_pattern)

#Search for Emails
regex1= re.compile(r'\S+@\S+')
#Search for Phone Numbers
regex2 = re.compile(r'\d\d\d[-]\d\d\d[-]\d\d\d\d')

match_list=[]

for file in folder_contents:

    if re.search(r".*(?=pdf$)",file):
        #this is pdf
        with open(file, 'rb') as pdfFileObj:
            pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 
            pageObj = pdfReader.getPage(0)  
            content = pageObj.extractText()
            read_file = open(file,'rb')
            #print("{}".format(file))

    elif re.search(r".*(?=csv$)",file):
        #this is csv
        with open(file,"r+",encoding="utf-8") as csv:
            read_file = csv.read()
            #print("{}".format(file))
    elif re.search(r"/jupyter",file):
        print("wow")
    elif re.search(r"/scikit",file):
        print("wow")
    else:
        read_file = open(file, 'rb').read()
       #print("{}".format(file))
        continue
    if regex1.findall(read_file) or regex2.findall(read_file):
                print(read_file)

我设法编写了以下代码,但它给出了以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-39-f614d35e0441> in <module>()
     38        #print("{}".format(file))
     39         continue
---> 40     if regex1.findall(read_file) or regex2.findall(read_file):
     41                 print(read_file)

TypeError: expected string or bytes-like object

有什么办法可以让它在没有错误的情况下工作?

标签: pythonregexglobpypdf2os.path

解决方案


首先,我向其他回答这个问题的人道歉,因为我会说一些关于 OP 前一个问题的事情。

关于 OP,你不应该不假思索地复制代码。

Content是您已经阅读的页面。这意味着您的代码应该是read_file = content. 以及我为什么写read_file = #,因为我认为你会添加额外的代码。但它不应该再次读取相同的文件。

with open(file, 'rb') as pdfFileObj:
        pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 
        pageObj = pdfReader.getPage(0)  
        content = pageObj.extractText()
        read_file = open(file,'rb') 
        #^---^---^ according to your former question, `read_file` should  be `content`

而且还会出现其他问题。你应该continueprint("wow").

elif re.search(r"/jupyter",file):
    print("wow")
elif re.search(r"/scikit",file):
    print("wow")

否则您的代码将继续运行,然后发生错误。因为你什么都没读。

if regex1.findall(read_file) or regex2.findall(read_file):
    print(read_file)

推荐阅读