2017-06-13 39 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

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

相關問題