首页 > 解决方案 > 将每 3 行作为一个元素并将其存储在一个元组中?

问题描述

我在文本文件中有以下内容。

Subject: Security alert

From: Google <no-reply@accounts.google.com>

To: example@email.com

Subject: Finish setting up your new Google Account

From: Google Community Team <googlecommunityteam-noreply@google.com>

To: example@email.com

Subject: Security alert

From: Google <no-reply@accounts.google.com>

To: example@email.com

我想将前三行存储在一个元组中,接下来的 3 行存储在另一个元组中,依此类推,如下所示。[预期输出]

['Subject: Security alert', 'From: Google <no-reply@accounts.google.com>', 'To: example@email.com']
['Subject: Finish setting up your new Google Account', 'From: Google Community Team <googlecommunityteam-noreply@google.com>', 'To: example@email.com']
['Subject: Security alert', 'From: Google <no-reply@accounts.google.com>', 'To: example@email.com']

我尝试使用以下代码,但是我在下面尝试如何使用“每一行”而不是“每个单词”时遗漏了。

with open('input.txt') as f:
     result = map(str.split, f)
     t = tuple(result)
     print(t)

# Unexpected output
(['Subject:', 'Security', 'alert'], [], ['From:', 'Google', '<no-reply@accounts.google.com>'], [], ['To:', 'pavan.python1393@gmail.com'], [], ['Subject:', 'Finish', 'setting', 'up', 'your', 'new', 'Google', 'Account'], [], ['From:', 'Google', 'Community', 'Team', '<googlecommunityteam-noreply@google.com>'], [], ['To:', 'pavan.python1393@gmail.com'], [], ['Subject:', 'Security', 'alert'], [], ['From:', 'Google', '<no-reply@accounts.google.com>'], [], ['To:', 'pavan.python1393@gmail.com'], [])

标签: pythonpython-3.xtuples

解决方案


这保留了之间的界限。这就是为什么它抓取六行而不是三行。

text="""Subject: Security alert

From: Google <no-reply@accounts.google.com>

To: example@email.com

Subject: Finish setting up your new Google Account

From: Google Community Team <googlecommunityteam-noreply@google.com>

To: example@email.com

Subject: Security alert

From: Google <no-reply@accounts.google.com>

To: example@email.com"""


lines = text.split('\n')
emails=[]

while lines:
    bunch=lines[:6]
    (esubj,efrom,eto)=bunch[0],bunch[2],bunch[4]
    e=(esubj,efrom,eto)
    print(e)
    assert "ubject" in esubj and "rom" in efrom and "To:" in eto
    emails.append((e))
    lines=lines[6:]
print(emails)

推荐阅读