gpt4 book ai didi

python - 如何在 Python 中将可变长度值追加到列表中

转载 作者:行者123 更新时间:2023-12-01 02:38:42 25 4
gpt4 key购买 nike

我有一个包含如下输入的文件:

host1 192.168.100.24
user1@abc.com host2 192.168.100.45 host7 192.168.100.40 host3 192.168.100.34 host4 192.168.100.20
user2@xyz.com host8 192.168.100.48 host6 192.168.100.43 host10 192.168.100.37
host5 192.168.100.24 host9 192.168.100.33

预期输出:

no_email: 
host1 192.168.100.24
host5 192.168.100.24
host9 192.168.100.33
user1@abc.com:
host2 192.168.100.45
host7 192.168.100.40
host3 192.168.100.34
host4 192.168.100.20
user2@xyz.com:
host8 192.168.100.48
host6 192.168.100.43
host10 192.168.100.37

代码:

def get_contacts(filename):

emails = []
hostname = []
ip = []
with open(filename,'r') as contacts_file:
for a_contact in contacts_file:
match = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', a_contact.split()[0])
if match == None:
emails.append('no_email')
hostname.append(a_contact.split()[0])
ip.append(a_contact.split()[1])
line_length = a_contact.count(' ')
elif line_length > 1:
emails.append(a_contact.split()[0])
hostname.append(a_contact.split()[1])
ip.append(a_contact.split()[2])
else:
emails.append(a_contact.split()[0])
hostname.append(a_contact.split()[1])
ip.append(a_contact.split()[2])
return emails, hostname, ip

我只想返回主机名和 IP 列表,这些列表将用于发送到从列表返回的指定电子邮件地址。任何人都可以帮助我如何轻松地完成它吗?谢谢。

最佳答案

首先安装validate_email模块具有:

$pip3 install validate_email

然后:

from validate_email import validate_email

result = {}
with open('file.txt') as f:
for line in f:
words = line.split()
if validate_email(words[0]): # If first word of the line is a valid email, lets store data on the result dict using the email as key.
email = words[0]
words = words[1:]
else:
email = 'no_email'

hosts_emails = [(words[i], words[i+1]) for i in range(0, len(words) - 1, 2)]
(result.setdefault(email, [])).append(hosts_emails)

print(result)

输出:

{'no_email': [[('host1', '192.168.100.24')], [('host5', '192.168.100.24'), ('host9', '192.168.100.33')]], 'user1@abc.com': [[('host2', '192.168.100.45'), ('host7', '192.168.100.40'), ('host3', '192.168.100.34'), ('host4', '192.168.100.20')]], 'user2@xyz.com': [[('host8', '192.168.100.48'), ('host6', '192.168.100.43'), ('host10', '192.168.100.37')]]}

关于python - 如何在 Python 中将可变长度值追加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45951789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com