【问题标题】:Add a character on a list if a situation presents如果出现情况,在列表中添加一个角色
【发布时间】:2017-01-26 10:49:37
【问题描述】:

在这里输入代码我有这个脚本:

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

由于我想拆分电子邮件和密码,我想,如果尝试不起作用(所以“:”不在文件的行中(并且account[1] 不存在) ),在文件中每封电子邮件的“.com”之后添加“:”。这可能吗?

第三个和第四个帐户的输出应该是:

email3@email.com:test3
email4@email.com:test4

【问题讨论】:

  • 如果电子邮件地址不以“com”结尾怎么办?
  • 创建此帐户列表的人有些错误
  • 什么是 test1?
  • 账号密码
  • 我注意到您已经用几乎相同的代码提出了一个问题,但问题不同,收集了答案(其中一个是我的),然后删除了该问题。现在这篇文章的代码包含了我对前面提到的问题的解决方案。在收到答案后提出问题并删除它不是 Stack Exchange 网络(尤其是 Stack Overflow)的工作方式。

标签: python list python-3.x for-loop split


【解决方案1】:

您可以使用正则表达式来拆分行:

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))

【讨论】:

    【解决方案2】:

    您可以在代码中添加correct_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)]
    

    【讨论】:

    • 您的方法工作正常,但如果有像“e.mail@email.com:test”这样的电子邮件,它会转换为:“em:ail@email.com”.. 我该怎么做解决这个问题?
    • 你确定吗?我刚刚尝试过,但没有。 In [8]: correct_accounts(['e.mail@email.com:test']) Out[8]: ['e.mail@email.com:test'] 它会跳过所有包含 : 的字符串,因此它只是将它们作为输入返回。
    猜你喜欢
    • 2021-06-11
    • 2021-01-19
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2021-07-27
    • 2022-11-27
    • 1970-01-01
    相关资源
    最近更新 更多