Substitute parenthesis for their regular expression

心不动则不痛 提交于 2019-12-24 01:18:10

问题


I'm trying to copy a file,

>>> 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)

But must first replace the spaces and parenthesis before the open function will work:

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

spaces ' ' --> '\ ' parenthesis '(' --> '\(' etc.

Replacing the spaces work:

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

but parenthesis return an error:

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

Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 151, in sub return _compile(pattern, flags).sub(repl, string, count) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 244, in _compile raise error, v # invalid expression sre_constants.error: unbalanced parenthesis

Am I replacing parenthesis correctly?

Also, when using re.escape() for this, the file is not returned correctly. So it is not an alternative.


回答1:


( has special meaning in regular expressions (grouping), you have to escape it:

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

or, since you don't use regex features for the replacement:

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



回答2:


The regular expression r'(' is translated as start a capturing group. Which is why Python is complaining.

If all you are doing is replacing spaces and parenthesis then maybe just string.replace will do ?




回答3:


Alternatively, if you avoid calling a shell (os.system) to do the copy, you don't need to worry about escaping spaces and other special characters,

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)



回答4:


  1. Use shutil.copy to copy files, rather than calling the system.
  2. Use subprocess rather than os.system - it avoids calling into the shell, so doesn't need the quoting.


来源:https://stackoverflow.com/questions/7053780/substitute-parenthesis-for-their-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!