Python3 重新格式化文件名的代码

Python3 code that reformats file names

# Regex pattern
filePattern = re.compile(r'''
    (#LPy3THW_Ex)
    (\d){1,3}
    (_macOS|_Windows)?
    (\.mp4)
    ''', re.VERBOSE)

我正在编写一个程序,旨在将 "LPy3THW_Ex6.mp4" 简化为 "ex6.mp4"。当我 运行 它时,下面是错误信息。我不确定问题出在哪里以及如何解决。

Traceback (most recent call last):
  File "file_rename.py", line 13, in <module>
    ''', re.VERBOSE)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 233, in compile
    return _compile(pattern, flags)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 301, in _compile
    p = sre_compile.compile(pattern, flags)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_compile.py", line 562, in compile
    p = sre_parse.parse(p, flags)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 855, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 416, in _parse_sub
    not nested and not items))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 768, in _parse
    source.tell() - start)
sre_constants.error: missing ), unterminated subpattern at position 2 (line 2, column 2)

当前错误是由于 # 符号在使用 re.VERBOSE 选项编译的正则表达式模式中启动内联注释。

您应该转义它(如果 # 应该作为文字散列字符出现在字符串中)或删除它(如果在该上下文中该符号不应该出现在字符串中)。另外,acc。对于示例 input/output,您应该删除 # 并重新排列捕获组,可能类似于:

filePattern = re.compile(r'''^
    LPy3THW_
    (
      Ex\d{1,3}
      (?:_macOS|_Windows)?
      \.mp4
    )
    $''', re.VERBOSE)
print(filePattern.sub(r"", s).lower())
# => ex6.mp4

请注意,(\d){1,3} 创建了一个重复的捕获组,并且只存储组中的最后一位数字。我添加了锚点来匹配整个字符串,只是为了演示目的(因为我在这里使用 re.sub)。

但是,您似乎可以将 _ 分成两部分并得到最后一项:

s.split('_', 2)[-1].lower() # => ex6.mp4

Python demo