python使用两种方式将xxxx@qq.com转换为qq.com@xxxx

有次去面试,面试官出了一道题,要求当场写出来,使用正则与非正则两种方法:一个txt文件里面写了很多邮箱账号:

12345@qq.com,要求用学过的语言,将邮箱账号转换输出为qq.com@12345。

渣渣的自己当时回答的并不好~

1、使用正则方法

import re

filename=r'C:UsersxxDesktopmail.txt'
f=open(filename,mode='r+',encoding='utf-8')
pattern1='^[0-9a-zA-z]{0,19}'  #匹配@前面的字符串
pattern2='[0-9a-zA-Z]{1,13}.[com,cn,net]{1,3}$'  #匹配@后面的字符串
lines=f.readlines()
for line in lines:
  part1=re.search(pattern1,line)  #使用search方法进行匹配
  part2=re.search(pattern2,line)
  f.writelines(part2.group(0)+'@'+part1.group(0)+' ')  #结果写回,group()获取匹配到的值,‘ ’换行写入每条数据

f.close()

2、使用字符串切割和拼接方法

filename=r'C:UsersqazDesktopmail.txt'

mail_list=[]
f=open(filename,mode='r+',encoding='utf-8')
lines=f.readlines()

for line in lines:
  content=line.strip(' ').split('@') #使用split切割字符串
  mail_list.append(content)#用列表存储切割的字符串
for i in mail_list:
  f.writelines('@'.join(i[::-1])+' ') #遍历列表,将列表里面的元素(也是列表)倒序后与@拼接,结果写回txt

f.close()

原文地址:https://www.cnblogs.com/nimantou/p/11820784.html