0

我在这里有一段代码,它使用 gmail POP 来解析来自文本消息 (1xxxxxxxxx7@vtext.com) 的消息。我希望解析器能够在消息中搜索多个字符串,并针对每个不同的字符串相应地运行代码。现在,解析器设置为查找带有“谢谢”的序列,但我不知道如何扩展它,因为我对 python 非常陌生。我的代码如下:

import poplib
from email import parser

pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('xxxxxxxxxxxxx')
pop_conn.pass_('xxxxxxxxxxxxx')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(Thankyou) for Thankyou in messages]
for message in messages:
    print 'Data Received'
pop_conn.quit()
4

2 回答 2

0

您提供的代码片段使用列表推导 - Python 中最强大的运算符。如果你想写 Python,你必须学习它们。这里是开始

至于您的问题-ThankYou 这里只是一个变量名,没有任何意义。

于 2014-04-01T05:48:54.033 回答
0

看起来您正在为列表推导而苦苦挣扎。

#List comprehension
messages = [parser.Parser().parsestr(Thankyou) for Thankyou in messages]

#Equivalent for loop
#Temporary list
temp = []

#Loop through all elements in messages
for Thankyou in messages:
  #If parsestr returns True for the current element (i.e. it's the string you're looking for)
  if parser.Parser().parsestr(Thankyou):
    temp.append(Thankyou)

#Overwrite the messages list with the temporary one
messages = temp

如您所见,列表推导更加简洁易读。它们在 Python 代码中被大量使用,但并不可怕。只需将它们视为遍历给定容器中每个元素的 for 循环。

为了搜索更多标记,您似乎需要编辑在遇到要查找的字符串时parsestr()返回的方法。True

于 2014-04-01T08:18:16.183 回答