简体   繁体   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?

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: 我需要它从上面的代码中取出打印出的内容并拉出最后两个单词,在这个例子中将Run newscript88.py并将其标记为一个字符串,以便稍后将其放入如下代码中:

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: 从字面上看,它会看起来是从电子邮件消息的最后2个单词然后它将最后2个单词放入此:

    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? 你想要身体的最后两个单词,你在变量body作为一个字符串,对吗?

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'] . 如果你打印出来,你会得到类似['Run', 'newscript88.py'] To put that back into a string, just use join : 要将其放回字符串中,只需使用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. 既然你不是一个* NIX系统上,我不能建议tee荷兰国际集团脚本和tail荷兰国际集团的文件。

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 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从python的此列表中选取特定元素? - how can i take a specific element from this list in python? 如何从 Python 中的单词列表中获取嵌入? - How can I get the embeddings from a list of words in Python? 如何从列表中获取python中列表的第一个值和最后一个值? - How do I take the first value and the last value from a list with a list in python? 如何从python列表制作树状菜单 - How can i make the tree like menus from python list 如何判断python变量是字符串还是列表? - How can I tell if a python variable is a string or a list? 如何判断未定义的变量是否在Python列表中? - How can I tell if an undefined variable is in a Python list? 如何从python中的列表中计算单词列表 - How to count a list of words from a list in python 如何使用Python从单词列表中删除不需要的字符并将其清除到另一个列表中? - How can I remove unwanted characters from a words list and put them cleared in another list using Python? 我如何告诉python我的数据结构(二进制)是什么样子,以便我可以绘制它? - How do I tell python what my data structure (that is in binary) looks like so I can plot it? 如何从 PYTHON I 中以“A”开头的列表中提取单词? - How do I extract words from a list that start with “A” in PYTHON I?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM