简体   繁体   中英

How can I tell python to take the last 2 words from an email that is in a list like structure but is not a list defined by python because it changes?

There is more to the code but I have it sort and read a specific email (but this email message changes and more things are added to the email message in an ordered format that looks like a list but is not a physical list that is able to be labeled..)

for num in data[0].split():
        typ, msg_data = conn.fetch(num, '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_string(response_part[1])
                subject=msg['subject']                   
                payload=msg.get_payload()
                body=extract_body(payload)
                print(body)
    #the portion of the code is these sources:unutbu and Doug Hellmann's tutorial on  imaplib

when it prints it prints:

Run script8.py


Run task9.py


Play asdf.mp3


Run unpause.py

but it changes so if I ran it ten minutes from now it may say:

Run script8.py


Run task9.py


Play asdf.mp3


Run unpause.py


Run newscript88.py

And I need it to take what is printed from the above code and pull the last 2 words which in this example would be Run newscript88.py and label it as a string to later be put into code like this:

os.startfile('Run newscript88.py')

So literally it would look take the last 2 words from the email message then it would put those last 2 words into this:

    os.startfile('last 2 words')

You want the last two words from the body, which you have as a string in the variable body , right?

The exact answer depends on how you define "word", but here's a very simple answer:

lastTwoWords = body.split()[-2:]

If you print that, you'll get something like ['Run', 'newscript88.py'] . To put that back into a string, just use join :

os.startfile(' '.join(lastTwoWords))

From your sample data, it seems at least possible that the last "word" could contain spaces, and what you really want is the two words on the last line… so maybe you want something like this:

lastLine = body.split('\n')[-1]
lastTwoWords = lastLine.split(None, 1)

Try something along the following lines:

import re
pat = re.compile('\w+ \w+[.]*$') # not very good regex
here_text = r'''here is some text
with lots of words, of which I only
want the LJ;lkdja9948 last two'''
i = pat.search(here_text)
i.group()
>> 'last two'

Since you're not on a *NIX system, I can't suggest tee ing your script and tail ing the file.

However, I would suggest the use of a buffer in your program that holds only two items:

class Buffer:
    def __init__(self):
        self.items = []
    def add(self, item):
        self.items.append(item)
        self.items = self.items[-2:]
    def __str__(self):
        return "[%s, %s]" %(self.items[0], self.items[1])
    def __getitem__(self, i):
        return self.items[i]

Use this buffer in your code and add to it just before you print out your values. Then, at any time, the values in your buffer will be "the last two values"

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM