0

I have a snippet of code here that uses gmail POP to to parse messages coming from a text message (1xxxxxxxxx7@vtext.com). I want the parser to be able to search for multiple strings in the message, and run code accordingly per each different string. Right now, the parser is set to find sequences with 'Thank you' but I don't know how to expand on this as I am extremely new to python. My code is as follows:

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()
SuperAdmin
  • 538
  • 2
  • 7
  • 20

2 Answers2

0

The code snippet you provided uses list comprehensions - the most powerful operator in Python. You must learn them if you want to write Python. Here is the beginning.

As of your question - ThankYou here is just a variable name, it means nothing.

0

It looks like you're struggling with list comprehensions.

#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

As you can see, the list comprehension is a lot more concise and readable. They're used a lot in Python code, but they're not scary. Just think of them as a for loop that iterates through every element in the given container.

In order to search for more tokens, it looks like you'll need to edit the parsestr() method to return True when you encounter the strings you are looking for.

CadentOrange
  • 3,263
  • 1
  • 34
  • 52
  • So if I wanted to add another output I would put something like this? 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) elsif parser.Parser().parsestr(Shutdown): #Run a shutdown code – SuperAdmin Apr 01 '14 at 12:44