将括号替换为正则表达式

2 投票
4 回答
3327 浏览
提问于 2025-04-16 23:33

我正在尝试复制一个文件,

>>> originalFile = '/Users/alvinspivey/Documents/workspace/Image_PCA/spectra_text/HIS/jean paul test 1 - Copy (2)/bean-1-aa.txt'
>>> copyFile = os.system('cp '+originalFile+' '+NewTmpFile)

但在打开这个文件之前,我必须先替换掉文件路径中的空格和括号:

/Users/alvinspivey/Documents/workspace/Image_PCA/spectra_text/HIS/jean\ paul\ test\ 1\ -\ Copy\ \(2\)/bean-1-aa.txt

空格 ' ' --> '\ ' 括号 '(' --> '\(' 等等。

替换空格是成功的:

>>> originalFile = re.sub(r'\s',r'\ ', os.path.join(root,file))

但是替换括号时却出现了错误:

>>> originalFile = re.sub(r'(',r'\(', originalFile)

错误追踪(最近的调用在最前面): 文件 "", 第 1 行, 在 文件 "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", 第 151 行, 在 sub return _compile(pattern, flags).sub(repl, string, count) 文件 "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", 第 244 行, 在 _compile raise error, v # 表达式无效 sre_constants.error: 括号不平衡

我替换括号的方式对吗?

另外,当我使用 re.escape() 来处理这个问题时,文件也没有正确返回。所以这也不是一个可行的方案。

4 个回答

2

另外,如果你不通过调用命令行(os.system)来进行复制操作,就不需要担心如何处理空格和其他特殊字符了。

import shutil

originalFile = '/Users/alvinspivey/Documents/workspace/Image_PCA/spectra_text/HIS/jean paul test 1 - Copy (2)/bean-1-aa.txt'
newTmpFile = '/whatever.txt'
shutil.copy(originalFile, newTmpFile)
2

这个正则表达式 r'(' 是用来表示开始一个捕获组的。这就是为什么Python会报错的原因。

如果你只是想替换空格和括号的话,或许直接用 string.replace 就可以了?

2

( 在正则表达式中有特殊的含义(用于分组),所以你需要对它进行转义:

originalFile = re.sub(r'\(',r'\(', originalFile)

或者,因为你在替换时并没有使用正则表达式的功能:

originalFile = re.sub(r'\(','\(', originalFile)

撰写回答