【问题标题】:Python: Email content configuration filePython:电子邮件内容配置文件
【发布时间】:2012-01-04 11:42:07
【问题描述】:

我希望能够将包含各种内容的配置文件邮寄出去。每封电子邮件都需要包含主题和正文,并带有换行符。

例如:

[Message_One]
Subject: Hey there
Body: This is a test
      How are you?
      Blah blah blah

      Sincerely,
      SOS

[Message_Two]
Subject: Goodbye
Body: This is not a test
      No one cares
      Foo bar foo bar foo bar

      Regards

如何让它与 Python 一起作为配置文件使用,以在内容之间随机选择和/或通过其定义的名称(Message_One、Message_Two)抓取一个?

谢谢

【问题讨论】:

    标签: python random ini


    【解决方案1】:

    可能是这样的:

    from ConfigParser import ConfigParser
    import random
    
    conf = ConfigParser()
    conf.read('test.conf')
    
    mail = random.choice(conf.sections())
    print "mail: %s" % mail
    print "subject: %s" % conf.get(mail, 'subject')
    print "body: %s" % conf.get(mail, 'body')
    

    只需选择带有random.choice(conf.sections()) 的随机部分名称即可。 random.choice 函数将从序列中选择一个随机元素——sections 方法将返回所有部分名称,即["Message_One", "Message_Two"]。然后,您可以使用该部分名称来获取您需要的其他值。

    【讨论】:

    • 谢谢。看起来比 kev 的目标要简单得多,但两者都按预期工作。
    • @mikeyy:如果你有一个 ini 文件格式的配置文件,那么你应该使用ConfigParser 来阅读它——如果你有别的东西,那么你必须自己动手像上面的 kev 那样的代码。
    • 我有别的事情,决定使用kev的代码。不过,我注意到你们两个之间的一件事,它在问候之前没有识别出额外的换行符,这只是一个中断。
    【解决方案2】:
    #!/usr/bin/env python3
    from re import match
    from collections import namedtuple
    from pprint import pprint
    from random import choice
    
    Mail = namedtuple('Mail', 'subject, body')
    
    def parseMails(filename):
        mails = {}
        with open(filename) as f:
            index = ''
            subject = ''
            body = ''
            for line in f:
                m = match(r'^\[(.+)\]$', line)
                if m:
                    if index:
                        mails[index] = Mail(subject, body)
                    index = m.group(1)
                    body = ''
                elif line.startswith('Subject: '):
                    subject = line[len('Subject: '):-1]
                else:
                    body += line[len('Body: '):]
            else:
                mails[index] = Mail(subject, body)
        return mails
    
    mails = parseMails('mails.txt')
    index = choice(list(mails.keys()))
    mail = mails[index]
    pprint(mail)
    

    Mail(subject='Goodbye', body='This is not a test\nNo one cares\nFoo bar foo bar foo bar\nRegards\n')
    
    • 解析邮件
    • 随机选择一封邮件

    【讨论】:

    • 谢谢,按预期工作,并允许我在需要时进行调整。
    • 知道为什么在问候之前只有一个换行符,而不是两个吗?
    • @mikeyy body += line[len('Body: '):]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2015-02-26
    • 2012-06-27
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    相关资源
    最近更新 更多