Python Regex 匹配文件列表中的文件(出错)

标签 python regex

我正在尝试使用 Python 中的正则表达式将文件(保存为字符串,即“/volumes/footage/foo/bar.mov”)与我创建的包含文件列表的日志文件相匹配。但是当我运行脚本时,它给我这个错误:sre_constants.error: unbalanced parenthesis。我使用的代码是这样的:

读取文件:

theLogFile = The_Root_Path + ".processedlog"
if os.path.isfile(theLogFile):
        the_file = open(theLogFile, "r")
    else:
        open(theLogFile, 'w').close()
        the_file = open(theLogFile, "r")
    the_log = the_file.read()
    the_file.close()

然后在 for 循环中,我将 the_file 变量重新分配(我没有意识到我在做这个,直到我发布了这个问题)文件(通过运行文件夹及其子集并获取所有文件名获得),然后尝试使用正则表达式查看该文件名是否存在于日志文件中:

for the_file in filenamelist:
    p = re.compile(the_file, re.IGNORECASE)
    m = p.search(the_log)

每次它遇到代码的 re.compile() 部分时,它都会吐出该错误。如果我尝试将其删除并使用 re.search(the_file, the_log),它仍然会吐出该错误。我不明白我怎么会因此得到不平衡的括号。

最佳答案

正则表达式模式在哪里?您是否尝试使用一个文件中包含的文件名作为模式来搜索另一个文件?如果是这样,您将希望通过 the_file 来执行类似

的操作
for the_pattern in the_file:
    p = re.compile(the_pattern, re.IGNORECASE)
    m = p.search(the_log)
    ...

根据 the Python re.compile documentationre.compile() 的第一个参数应该是作为字符串的正则表达式模式。

但是 open() 的返回值是一个文件对象,您将其分配给 the_file 并传递给 re.compile() ....

关于Python Regex 匹配文件列表中的文件(出错),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2344193/

相关文章:

python - NumPy 中的多处理

python - 如何从 Python 获取 UTC 格式的文件修改日期

python - OS X 上的 Virtualenv 安装

python - basemap 返回空白 map

regex - 正则表达式查找字符连续次数少于x次且多于y次的字符?

python - 如何用正则表达式表达 'repeat this part'?

python - 404 错误处理程序中缺少 Flask 上下文

Jquery 表单验证 - 电话号码

javascript - 使用javascript正则表达式替换文本中的相似字符串

javascript - 正则表达式在 URL 地址测试中失败