我希望能够有一个包含各种内容的配置文件。每封电子邮件都需要包含一个主题和一个正文,并带有新行。
例如:
[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)获取?
由于
答案 0 :(得分:3)
也许是这样的:
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"]
。然后,您可以使用该部分名称来获取所需的其他值。
答案 1 :(得分:1)
#!/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')