文件内容替换
文件内容替换
import re
def replace_match(filename, pattern, replacement_func):
with open(filename, 'r') as file:
content = file.read()
new_content = re.sub(pattern, lambda x: replacement_func(x.group(0), "replacement_string"), content)
with open(filename, 'w') as file:
file.write(new_content)
def replacement_func(match, replacement_string):
# Do something with the match and replacement_string
return "replacement_result"
# Example usage
replace_match('example.txt', r'pattern', replacement_func)