Изначально имея рабочий скрипт, подобный этому, чтобы go поверх csv-файлов в папке подставить подстроку:
import fileinput
import os
import glob
#### Directory and file mask
this = r"C:\work\PythonScripts\Replacer\*.csv"
output_folder = "C:\\work\\PythonScripts\\Replacer\\"
#### Get files
files = glob.glob(this)
#### Section to replace
text_to_search = 'z'
replacement_text = 'ZZ_Top'
#### Loop through files and lines:
for f in files:
head, tail = os.path.split(f)
targetFileName = os.path.join(head, output_folder, tail)
with fileinput.FileInput(targetFileName, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_to_search, replacement_text), end='')
Пришла необходимость заменить несколько кавычек Word и длинный дефис. Поэтому я подумал об использовании чего-то вроде этого в приведенном выше цикле:
s = '’ ‘ ’ ‘ ’ – “ ” “ – ’'
print(s)
print(s.replace('’', '\'').replace('‘', '\'').replace('–','-').replace('“','"').replace('”','"'))
==>
’ ‘ ’ ‘ ’ – “ ” “ – ’
' ' ' ' ' - " " " - '
Но потом я наткнулся на следующий комментарий использования подфункции регулярного выражения: { ссылка }
Итак, я попробовал, и он работал нормально сам по себе:
import re
def multisub(subs, subject):
# "Simultaneously perform all substitutions on the subject string."
pattern = '|'.join('(%s)' % re.escape(p) for p, s in subs)
substs = [s for p, s in subs]
replace = lambda m: substs[m.lastindex - 1]
return re.sub(pattern, replace, subject)
print(multisub([('’', '\''), ('‘', '\''), ('–','-'), ('“','"'), ('”','"')], '1’ 2‘ 1’ 2‘ 1’ 3– 4“ 5” 4“ 3– 2’'))
==>
1' 2' 1' 2' 1' 3- 4" 5" 4" 3- 2'
Но как только Я прикрепил его к исходному сценарию, который он запускает, но не изменяет файл:
import fileinput
import os
import glob
import re
#### Directory and file mask
this = r"C:\work\PythonScripts\Replacer\*.csv"
output_folder = "C:\\work\\PythonScripts\\Replacer\\"
#### RegEx substitution func
def multisub(subs, subject):
# "Simultaneously perform all substitutions on the subject string."
pattern = '|'.join('(%s)' % re.escape(p) for p, s in subs)
substs = [s for p, s in subs]
replace = lambda m: substs[m.lastindex - 1]
return re.sub(pattern, replace, subject)
#### Get files
files = glob.glob(this)
#### Loop through files and lines:
for f in files:
head, tail = os.path.split(f)
targetFileName = os.path.join(head, output_folder, tail)
with fileinput.FileInput(targetFileName, inplace=True, backup='.bak') as file:
for line in file:
print(multisub([('’', '\''), ('‘', '\''), ('–','-'), ('“','"'), ('”','"')], line), end='')
Что здесь может быть не так?