python - 读取目录中的所有文件并输出其中包含某些正则表达式的文件
问题描述
我正在尝试读取目录中的所有文件并输出包含正则表达式的文件以及每个文件中的正则表达式。
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
有什么办法可以让它在没有错误的情况下工作?
解决方案
首先,我向其他回答这个问题的人道歉,因为我会说一些关于 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)
推荐阅读
- pip - 参数包的类型
我们无法在 Ansible 中转换为列表错误 - html - 电话输入自动填充删除国际前缀
- mongodb - 如何在 Windows 上设置 MongoDB 日志轮换?
- java - 尝试调用虚拟方法 'void androidx.recyclerview.widget.RecyclerView.setAdapter
- c++ - 不同的输出取决于我是否打印返回值
- r - 如何在闪亮服务器的反应函数中添加多个输入变量?
- python - 从 index.ts 触发导出可执行脚本命令
- pandas - 在熊猫中单独计算时间增量
- f# - 如何通过在 F# 中为每个惰性对象创建值来转换其中包含惰性对象的异构数组(无反射)
- spring - 创建自己的配置类