Python 如果出现情况,请在列表中添加一个字符
我有这个剧本:Python 如果出现情况,请在列表中添加一个字符,python,list,python-3.x,for-loop,split,Python,List,Python 3.x,For Loop,Split,我有这个剧本: accounts = open("accounts.txt").readlines() y = [x.strip().split(":") for x in accounts] for position, account in enumerate(y): try: print ("Trying with: %s:%s @%d" % (account[0], account[1], position)) except: pass
accounts = open("accounts.txt").readlines()
y = [x.strip().split(":") for x in accounts]
for position, account in enumerate(y):
try:
print ("Trying with: %s:%s @%d" % (account[0], account[1], position))
except:
pass
它会打开一个文件(accounts.txt),其结构如下:
email1@email.com:test1
email2@email.com:test2
email3@email.comtest3
email4@email.comtest4
由于我想拆分电子邮件和密码,如果尝试不起作用(因此“:”不在文件行中(并且帐户[1]不存在)),我希望在文件中每个电子邮件的“.com”之后添加“:”。可能吗
第三和第四个账户的产出应为:
email3@email.com:test3
email4@email.com:test4
您可以使用正则表达式拆分行:
In [37]: s1 = 'email2@email.com:test2'
In [38]: s2 = 'email3@email.comtest3'
In [42]: regex = re.compile(r'(.+\.com):?(.*)')
In [43]: regex.search(s1).groups()
Out[43]: ('email2@email.com', 'test2')
In [44]: regex.search(s2).groups()
Out[44]: ('email3@email.com', 'test3')
在您的代码中:
regex = re.compile(r'(.+\.com):?(.*)')
with open("accounts.txt") as f:
for ind, line in enumerate(f):
try:
part1, part2 = regex.search(line.strip()).groups()
except:
pass
else:
print ("Trying with: {}:{} @{}".format(part1, part2, ind))
您可以在代码中添加一个
correct\u accounts
函数
def correct_accounts(accounts):
corr = []
for x in accounts:
if ':' not in x:
# Assuming all mail addresses end with .com
pos = x.find ('.com') + 4
corr.append(x [:pos] + ':' + x [pos:])
else:
corr.append(x)
return corr
并致电:
y = [x.strip().split(":") for x in correct_accounts(accounts)]
如果电子邮件地址不以“com”结尾该怎么办?关于谁制作了此帐户列表的一些错误什么是测试1?帐户密码我注意到您已经用几乎相同的代码问了一个问题,但问题不同,收集了答案(其中一个是我的),然后删除了该问题。现在,这篇文章的代码包含了我对前面提到的问题的解决方案。询问问题并在收到答案后将其删除并不是堆栈交换网络(尤其是堆栈溢出)的工作方式。您的方法可以正常工作,但如果存在类似“e”的电子邮件。mail@email.com:test”,将其转换为:“e.m:ail@email.com".. 我怎么解决这个问题?你确定吗?我只是试了一下,但没有成功<[8]中的代码>正确的账户(['e。mail@email.com:test'])Out[8]:['e。mail@email.com:test']它跳过包含
:
的所有字符串,因此它只是从输入中返回它们。