>>> a = "this is email: someone@mail.com and this one is another email foo@bar.com"
>>> re.sub('([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})', r'"\1"', a)
'this is email: "someone@mail.com" and this one is another email "foo@bar.com"'
更新:如果您有一个文件要替换其中每行的电子邮件,您可以这样使用readlines():
import re
with open("email.txt", "r") as file:
lines = file.readlines()
new_lines = []
for line in lines:
new_lines.append(re.sub('([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})', r'"\1"', line))
with open("email-new.txt", "w") as file:
file.writelines(new_lines)
你知道吗电子邮件.txt地址:
this is test@something.com and another email here foo@bar.com
another email abc@bcd.com
still remaining someone@something.com
电子邮件-新建.txt(运行代码后):
this is "test@something.com" and another email here "foo@bar.com"
another email "abc@bcd.com"
still remaining "someone@something.com"
您可以使用re.sub模块并像这样使用反向引用:
更新:如果您有一个文件要替换其中每行的电子邮件,您可以这样使用
readlines()
:你知道吗电子邮件.txt地址:
电子邮件-新建.txt(运行代码后):
相关问题 更多 >
编程相关推荐