簡體   English   中英

我如何告訴python從列表中的電子郵件中獲取最后2個單詞,但是不是python定義的列表,因為它發生了變化?

[英]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?

代碼還有更多內容,但是我對它進行了排序和讀取特定的電子郵件(但是這封電子郵件消息發生了變化,更多的東西以有序的格式添加到電子郵件中,看起來像列表但不是能夠的物理列表被標記..)

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

打印時打印:

Run script8.py


Run task9.py


Play asdf.mp3


Run unpause.py

但它改變了所以如果我從現在起十分鍾后運行它可能會說:

Run script8.py


Run task9.py


Play asdf.mp3


Run unpause.py


Run newscript88.py

我需要它從上面的代碼中取出打印出的內容並拉出最后兩個單詞,在這個例子中將Run newscript88.py並將其標記為一個字符串,以便稍后將其放入如下代碼中:

os.startfile('Run newscript88.py')

從字面上看,它會看起來是從電子郵件消息的最后2個單詞然后它將最后2個單詞放入此:

    os.startfile('last 2 words')

你想要身體的最后兩個單詞,你在變量body作為一個字符串,對嗎?

確切的答案取決於你如何定義“單詞”,但這是一個非常簡單的答案:

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

如果你打印出來,你會得到類似['Run', 'newscript88.py'] 要將其放回字符串中,只需使用join

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

從你的樣本數據來看,似乎至少有可能最后一個“單詞”可以包含空格,你真正想要的是最后一行的兩個單詞......所以也許你想要這樣的東西:

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

嘗試以下幾行:

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'

既然你不是一個* NIX系統上,我不能建議tee荷蘭國際集團腳本和tail荷蘭國際集團的文件。

但是,我建議在程序中使用只包含兩個項目的緩沖區:

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]

在代碼中使用此緩沖區,並在打印出值之前添加到緩沖區中。 然后,在任何時候,緩沖區中的值將是“最后兩個值”

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM