如果代碼為:
text = re.sub(r'(?<=[{])([a-z]+)6(?=[}])', r'\13', text)
上面代碼會報錯,因為沒有組合13,所以不能獲得組合13的內容。
但是我們要實現的是將{ni6}中的ni6替換成ni3,我們應該這么寫:
text = re.sub(r'(?<=[{])([a-z]+)6(?=[}])', r'\g<1>3', text)
另外,記錄我的批量替換代碼(將文件夾下的所有文件的拼音6都替換成3):
# -*- coding: utf-8 -*- import os import glob import shutil import re here = os.path.dirname(os.path.abspath(__file__)) for path in glob.glob(os.path.join(here, '**', '*'), recursive=True): if path.endswith('.py') or not os.path.isfile(path): continue print(path) dst_path = path + '.jacen_bak' os.rename(path, dst_path) # shutil.copy2(path, dst_path) try: with open(dst_path, 'r', encoding='utf-8') as f: text = f.read() text = re.sub(r'(?<=[{])([a-z]+)6(?=[}])', r'\g<1>3', text) with open(path, 'w', encoding='utf-8') as f: f.write(text) os.remove(dst_path) except UnicodeDecodeError as e: os.rename(dst_path, path) print(e, path)