【问题标题】:Add adding if/else to python parser添加添加 if/else 到 python 解析器
【发布时间】:2014-05-11 17:24:52
【问题描述】:

我在这里有一段代码,它使用 gmail POP 来解析来自文本消息 (1xxxxxxxxx7@vtext.com) 的消息。我希望解析器能够在消息中搜索多个字符串,并针对每个不同的字符串相应地运行代码。现在,解析器设置为查找带有“谢谢”的序列,但我不知道如何扩展它,因为我对 python 非常陌生。我的代码如下:

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

【问题讨论】:

    标签: python parsing poplib


    【解决方案1】:

    您提供的代码 sn-p 使用列表推导 - Python 中最强大的运算符。如果你想写 Python,你必须学习它们。 Here is the beginning

    关于您的问题-ThankYou 这里只是一个变量名,没有任何意义。

    【讨论】:

      【解决方案2】:

      看起来您正在为列表推导而苦苦挣扎。

      #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
      

      如您所见,列表推导更加简洁易读。它们在 Python 代码中被大量使用,但并不可怕。只需将它们视为遍历给定容器中每个元素的 for 循环。

      为了搜索更多令牌,您似乎需要编辑 parsestr() 方法以在遇到要查找的字符串时返回 True

      【讨论】:

      • 所以如果我想添加另一个输出我会放这样的东西?消息中的Thankyou:#If parsestr 为当前元素返回True(即,它是您要查找的字符串) if parser.Parser().parsestr(Thankyou): temp.append(Thankyou) elsif parser.Parser()。 parsestr(Shutdown): #运行一个关机代码
      猜你喜欢
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多