簡體   English   中英

用括號替換它們的正則表達式

[英]Substitute parenthesis for their regular expression

我正在嘗試復制文件,

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

但必須先替換空格和括號,然后打開 function 才會起作用:

/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) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 244, in _compile raise error, v # invalid表達式 sre_constants.error:不平衡括號

我是否正確替換了括號?

此外,當為此使用 re.escape() 時,文件不會正確返回。 所以它不是替代品。

(在正則表達式(分組)中具有特殊含義,您必須對其進行轉義:

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

或者,因為您不使用正則表達式功能進行替換:

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

正則表達式r'('被翻譯為啟動捕獲組。這就是 Python 抱怨的原因。

如果您所做的只是替換空格和括號,那么也許string.replace就可以了?

或者,如果您避免調用 shell (os.system) 進行復制,則無需擔心 escaping 空格和其他特殊字符,

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)
  1. 使用 shutil.copy 復制文件,而不是調用系統。
  2. 使用 subprocess 而不是 os.system - 它避免調用 shell,因此不需要引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM