如何调用自定义函数替换文件中匹配正则的指定值?
问题:替换文件中匹配正则的指定值
我有一个包含多条条目的文件,希望修改其中匹配[a-z]{3}[0-9]{3}格式的值,要求除需替换的值外,文件其余内容与原文件完全一致。
文件内容如下:
dn: uid=alan,cn=users,dc=mysite,dc=dc=com objectclass: organizationalPerson objectclass: person objectclass: top objectclass: inetOrgPerson uid: wpsadmin userpassword: wpsadmin specificattribute: abc123, cvb765 sn: admin givenName: fgh876 cn: wps admin dn: uid=alice,cn=users,dc=mysite,dc=dc=com objectclass: organizationalPerson objectclass: person objectclass: top objectclass: inetOrgPerson uid: wasadmin userpassword: wasadmin specificattribute: def456 sn: admin givenName: aaa000 cn: was admin dn: uid=lana,cn=users,dc=mysite,dc=dc=com objectclass: top objectclass: person objectclass: organizationalPerson objectclass: inetOrgPerson uid: wpsbind userpassword: wpsbind specificattribute: ghi789 sn: bind givenName: wps cn: wps bind
我想用字典中存储的对应值替换这类格式的值,现有代码片段如下,但不知道如何调用replacement函数:
#!/usr/bin/env python3 import re Dict = {'abc123': 'zzz999', 'cde456': 'xxx888', 'fgh789': 'www777'} # and so on... def replacement(val): val2 = Dict.get(val) return print(val2)
目前尝试的正则替换代码会把所有匹配项替换成固定值,不符合需求:
with open('file.txt', "r+") as f: content = f.read() content_new = re.sub('[a-z]{3}[0-9]{3}', r'abc123', content) f.seek(0) f.write(content_new) f.truncate()
解决方案
你需要修正replacement函数的逻辑,并直接将函数作为re.sub的第二个参数传入,让正则引擎自动把每个匹配结果传给该函数处理。
修改后的完整代码:
#!/usr/bin/env python3 import re # 定义替换映射字典 replace_map = {'abc123': 'zzz999', 'cde456': 'xxx888', 'fgh789': 'www777', 'aaa000': 'bbb111'} def replacement(match): # 获取匹配到的字符串 matched_val = match.group() # 从字典取对应值,没有则返回原匹配值(避免替换不存在的项) return replace_map.get(matched_val, matched_val) with open('file.txt', "r+") as f: content = f.read() # 将replacement函数作为替换参数传入re.sub content_new = re.sub('[a-z]{3}[0-9]{3}', replacement, content) f.seek(0) f.write(content_new) f.truncate()
关键说明:
re.sub的第二个参数可以接收一个函数,该函数会接收每个匹配对象match,通过match.group()获取到匹配的字符串。- 修正后的
replacement函数不再使用print(这会返回None,导致替换成空),而是返回字典中对应的替换值,若字典中没有该匹配项则返回原字符串,保证不修改不需要替换的内容。 - 建议将变量名
Dict改为replace_map,符合Python命名规范。
内容的提问来源于stack exchange,提问作者PsyKoptiK
相关产品推荐
相关产品推荐

