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?

蹲街弑〆低调 提交于 2021-01-29 12:14:20

问题


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')

回答1:


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)



回答2:


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'



回答3:


Since you're not on a *NIX system, I can't suggest teeing your script and tailing 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



来源:https://stackoverflow.com/questions/13482586/how-can-i-tell-python-to-take-the-last-2-words-from-an-email-that-is-in-a-list-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!