Python - 将多行读取到列表中
大家好,我又卡住了,遇到了一些简单的问题。
我有一个文本文件,每个条目有多行,数据格式如下:
第一行:firstword word word word
第二行:wordx word word word interesting1 word word word word
第三行:wordy word word word
第四行:wordz word word word interesting2 word word word lastword
这个序列大概重复了一百次,其他的单词都一样,只有interesting1和interesting2不同,而且没有空行。interesting2和interesting1是相关的,但和其他的没有关系,我想把这两个有趣的项目连接起来,其他的都丢掉,比如:
interesting1 = interesting2
interesting1 = interesting2
interesting1 = interesting2
等等,每个序列一行。
每一行都以不同的单词开头。
我尝试读取文件,然后用“如果wordx在这一行”这样的语句来识别第一行有趣的内容,切出这个值,再找到第二行(“如果wordz在这一行”),切出这个值,然后把第二个值和第一个值连接起来。
不过这样做很笨拙,我不得不使用全局变量、临时变量等等,我相信一定有办法识别firstword和lastword之间的范围,并把它放到一个单一的列表中,然后一起切出这两个值。
任何建议都非常感谢,感谢你们的时间。
3 个回答
我在这里放了一堆检查,来看看你的数据布局是否正常。
C:\SO>type words.py
# sample pseudo-file contents
guff = """\
firstword word word word
wordx word word word interesting1-1 word word word word
wordy word word word
wordz word word word interesting2-1 word word word lastword
miscellaneous rubbish
firstword word word word
wordx word word word interesting1-2 word word word word
wordy word word word
wordz word word word interesting2-2 word word word lastword
firstword word word word
wordx word word word interesting1-3 word word word word
wordy word word word
wordz word word word interesting2-3 word word word lastword
"""
# change the RHS of each of these to reflect reality
FIRSTWORD = 'firstword'
WORDX = 'wordx'
WORDY = 'wordy'
WORDZ = 'wordz'
LASTWORD = 'lastword'
from StringIO import StringIO
f = StringIO(guff)
while True:
a = f.readline()
if not a: break # end of file
a = a.split()
if not a: continue # empty line
if a[0] != FIRSTWORD: continue # skip extraneous matter
assert len(a) == 4
b = f.readline().split(); assert len(b) == 9
c = f.readline().split(); assert len(c) == 4
d = f.readline().split(); assert len(d) == 9
assert a[0] == FIRSTWORD
assert b[0] == WORDX
assert c[0] == WORDY
assert d[0] == WORDZ
assert d[-1] == LASTWORD
print b[4], d[4]
C:\SO>\python26\python words.py
interesting1-1 interesting2-1
interesting1-2 interesting2-2
interesting1-3 interesting2-3
C:\SO>
在这种情况下,创建一个正则表达式来匹配重复的文本,并为你感兴趣的部分设置分组。这样你就可以使用findall来找到所有有趣的部分interesting1和interesting2。
像这样: import re
text = open("foo.txt").read()
RE = re.compile('firstword.*?wordx word word word (.*?) word.*?wordz word word word (.*?) word', re.DOTALL)
print RE.findall(text)
不过正如评论中提到的,使用islice的方法确实更简洁。
当然可以!请看下面的内容:
这个问题主要是关于如何在编程中处理一些特定的情况。很多时候,我们在写代码的时候会遇到一些错误或者意外的结果,这时候就需要找到解决办法。
在这个讨论中,大家分享了他们的经验和解决方案。有的人提到了一些常见的错误类型,比如说变量没有正确赋值,或者函数没有正确调用。这些都是初学者常常会碰到的问题。
还有人建议使用调试工具,这些工具可以帮助我们一步一步地检查代码,找出问题所在。调试就像是在检查一个拼图,看看哪里放错了。
总之,遇到问题不要慌,大家都经历过这些。多问问题,多尝试,慢慢就能掌握这些技巧了。
from itertools import izip, tee, islice
i1, i2 = tee(open("foo.txt"))
for line2, line4 in izip(islice(i1,1, None, 4), islice(i2, 3, None, 4)) :
print line2.split(" ")[4], "=", line4.split(" ")[4]