【发布时间】:2018-12-03 19:24:28
【问题描述】:
我正在尝试读取目录中的所有文件并输出包含正则表达式的文件以及每个文件中的正则表达式。
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
有什么方法可以让它在没有错误的情况下工作?
【问题讨论】:
-
the ones that contain the regexes您的任期无效。这些文件实际上并不包含正则表达式。您正在使用正则表达式来匹配文件中的文本。 -
你是什么意思?我正在尝试为两个正则表达式字符串过滤我的目录
-
什么?你说你想在一个字符串中找到一个正则表达式?这是语义,正则表达式在 target 字符串上工作,而不是相反。
-
我正在尝试匹配文件中的正则表达式模式
标签: python regex glob pypdf2 os.path