【发布时间】:2020-07-08 19:48:37
【问题描述】:
最初有这样的工作脚本来检查文件夹中的 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('”','"'))
==>
’ ‘ ’ ‘ ’ – “ ” “ – ’
' ' ' ' ' - " " " - '
但后来我遇到了以下使用正则表达式子函数的评论: https://stackoverflow.com/a/765835
所以我试了一下,它自己运行良好:
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='')
这里有什么问题?
【问题讨论】:
标签: python python-3.x regex