将电子邮件发送到子组/超级组 - 嵌套字典?

时间:2018-03-14 21:33:17

标签: python dictionary

我的文件包含以下记录。这代表群组名称:emailadd'

Group1: it@group.foobar.com, Group1: it@group.foobar.com  
Group2: man@foobar.com, Group2: man@foobar.com  
Group3: xyz@foobar.com, test-grp: yz@foobar.com, grp-t: new@foobar.com, test-contract: new_g@foobar.com, grp0: ij@foobar.com, grp8: turu@foobar.com  
Group_test: iu@foobar.com, gvgrp: in@foobar.com, rsgrp: ij@foobar.com, dev: mp@foobar.com, rs: uru@foobar.com  

假设第一个字段:email是supergrpup,其他是嵌套组 这意味着

Supegroups:

Group1: it@group.foobar.com  
Group2: man@foobar.com   
Group3: xyz@foobar.com  
Group_test: iu@foobar.com  

子群:

Group1: it@group.foobar.com 
Group2: man@foobar.com
test-grp: yz@foobar.com, grp-t: new@foobar.com, test-contract: new_g@foobar.com, grp0: ij@foobar.com, grp8: turu@foobar.com 
gvgrp: in@foobar.com, rsgrp: ij@foobar.com, dev: mp@foobar.com, rs: uru@foobar.com

现在我想向这些群组发送电子邮件以便解决(以':'分隔)

但是应该将电子邮件发送给超级组及其各自的子组

喜欢直线:

  Group3: xyz@foobar.com, test-grp: yz@foobar.com, grp-t: new@foobar.com, test-contract: new_g@foobar.com, grp0: ij@foobar.com, grp8: turu@foobar.com 

它应该向超级群组电子邮件和所有子群组电子邮件地址发送电子邮件,并在电子邮件正文中使用他们的群组名称。

To: xyz@foobar.com, yz@foobar.com, new@foobar.com, new_g@foobar.com, 
ij@foobar.com,  turu@foobar.com 

Body:
Failed because of groupnames :  Group3, test-grp, grp-t, test-contract, 
grp0, grp8 ---------> These are all  group associated with email specified 
in "To":

我不确定应该怎么做?我试图创建词典但又不起作用......

如果有人可以看看并帮助我,那将会很有帮助吗?

非常感谢 鲍勃

1 个答案:

答案 0 :(得分:0)

您可以使用regex和group解析字符串以创建嵌套字典列表:

import re
s = """
Group1: it@group.foobar.com, Group1: it@group.foobar.com  
Group2: man@foobar.com, Group2: man@foobar.com  
Group3: xyz@foobar.com, test-grp: yz@foobar.com, grp-t: new@foobar.com, test-contract: new_g@foobar.com, grp0: ij@foobar.com, grp8: turu@foobar.com  
Group_test: iu@foobar.com, gvgrp: in@foobar.com, rsgrp: ij@foobar.com, dev: mp@foobar.com, rs: uru@foobar.com
"""
listings = [re.findall('[a-zA-Z0-9\-\_]+(?=:\s)|(?<=:\s)[a-zA-Z0-9@\._]+', i) for i in filter(None, s.split('\n'))]
new_groups = [{**{i[0]:i[1]}, **{'subgroups':dict([(i[2:][b], i[2:][b+1]) for b in range(0, len(i)-2, 2)])}} for i in listings]
def get_flattened_listing(d):
   return [i for b in [[b] if not isinstance(b, dict) else get_flattened_listing(b) for a, b in d.items()] for i in b]

def send_email(structure, body='Testing new system'):
   yield from ['To: {}\n\nBody: {}'.format(', '.join(get_flattened_listing(i)), body) for i in structure]

for message in send_email(new_groups):
  print(message)
  print('-'*10)

输出:

To: it@group.foobar.com, it@group.foobar.com

Body: Testing new system
----------
To: man@foobar.com, man@foobar.com

Body: Testing new system
----------
To: xyz@foobar.com, yz@foobar.com, new@foobar.com, new_g@foobar.com, ij@foobar.com, turu@foobar.com

Body: Testing new system
----------
To: iu@foobar.com, in@foobar.com, ij@foobar.com, mp@foobar.com, uru@foobar.com

Body: Testing new system
----------