2017-06-13 35 views
1
import imaplib 
import re 
mail = imaplib.IMAP4_SSL("imap.gmail.com", 993) 
mail.login("****[email protected]","*****iot") 
while True: 
    mail.select("inbox") 
    status, response = mail.search(None,'(SUBJECT "Example")') 
    unread_msg_nums = response[0].split() 
    data = [] 
    for e_id in unread_msg_nums: 
     _, response = mail.fetch(e_id, '(UID BODY[TEXT])') 
     data.append(response[0][1].decode("utf-8")) 
     str1 = ''.join(map(str,data)) 
     #a = int(re.search(r"\d+",str1).group())   
     print(str1) 
    #for e_id in unread_msg_nums: 
     #mail.store(e_id, '+FLAGS', '\Seen') 

当我**打印STR1我有这样的:阅读邮件正文,并把每一行中一些不同的变量

Temperature:time,5 
Lux:time,6 
Distance:time,3 

这是从电子邮件的文本,它的确定。这是树莓派做一些事情的配置信息。 对于温度,勒克斯和距离,我可以为它们中的每一个设置1-10个数字(分钟),并且该数字表示时间,例如在这段时间内循环中会发生什么。这一切都在电子邮件的一边。如何把每一行我一些不同的变量,并稍后检查?

**For example** 
string1= first line of message #Temperature:time,5 
string2= second line of message #Lux:time,6 
string3= third line of message #Distance:time,3 

这不是修复,第一行可能是力士,也可以是距离等。

+0

为什么不直接使用列表并将每行添加到它?之后你可以遍历它们。 –

回答

1

一个正则表达式的工作,真的(这种方法使用的字典理解):

import re 

string = """ 
Temperature:time,5 
Lux:time,6 
Distance:time,3 
""" 

rx = re.compile(r'''^(?P<key>\w+):\s*(?P<value>.+)$''', re.MULTILINE) 
cmds = {m.group('key'): m.group('value') for m in rx.finditer(string)} 
print(cmds) 
# {'Lux': 'time,6', 'Distance': 'time,3', 'Temperature': 'time,5'} 

你的命令发生的顺序并不重要,但它们需要是唯一的(否则它们将被下一场比赛覆盖)。之后,你可以用例如。 cmds['Lux']

+0

工作!非常感谢你!!! :) –

相关问题