Читать все файлы в каталоге и выводить файлы, которые содержат определенные регулярные выражения в них - PullRequest
0 голосов
/ 03 декабря 2018

Я пытаюсь прочитать все файлы в моем каталоге и вывести те, которые содержат регулярные выражения, а также то, что было регулярным выражением в каждом файле.

 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

Есть ли способ заставить это работать без ошибки?

Ответы [ 3 ]

0 голосов
/ 03 декабря 2018

С read() будет работать только open(filename).Просто замените это, и вы решите свою проблему.

read_file = open(file).read()
0 голосов
/ 04 декабря 2018

Сначала я прошу прощения у других людей, которые ответили на этот вопрос, потому что я скажу кое-что о предыдущем вопросе 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`

И будут другие проблемы.Вы должны добавить continue после print("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)
0 голосов
/ 03 декабря 2018

Замените код чтения файла следующим:

with open(File, mode='rb') as file:
    readFile = file.read()
...