python - 将每 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'], [])
解决方案
这保留了之间的界限。这就是为什么它抓取六行而不是三行。
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)
推荐阅读
- android - 尝试在 Google Play 控制台中预览我的应用版本并不断出错
- sql - sql这个查询语句的作用是什么
- google-cloud-platform - Google Cloud 存储文件的基本身份验证
- css - 如何使用 React Native 在静态图像上实现网格覆盖
- appkit - 如何设置 NSSearchToolbarItem 的初始宽度
- javascript - 带有返回字符串的 Jss 函数
- c# - net5 自包含的 exe 缺少一些系统 DLL
- windows - Git、OpenSSH、windows 7“致命:远程端意外挂断”
- android - 地图不显示当前位置
- delphi - 在 Spring4D 中是否可以注册通用接口?