如何使用python在文本文件中打印特定行

时间:2013-04-15 06:09:31

标签: python

这是我的输入文本文件,包含三个字段。 (描述,价值,极性)

this is good
01
positive
this is bad
-01
negetive
this is ok
00
neutral

所以我需要根据值字段获取所有描述。对于Ex:当我检查"This is good"的if条件时,我想打印"01"。有没有办法做到这一点。请建议我。

1 个答案:

答案 0 :(得分:0)

使用itertools中的grouper食谱以3行的方式遍历文件:

>>> from itertools import izip_longest, imap
>>> def grouper(n, iterable, fillvalue=None):
        "Collect data into fixed-length chunks or blocks"
        # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
        args = [iter(iterable)] * n
        return izip_longest(fillvalue=fillvalue, *args)


>>> with open('test.txt') as f:
    d = dict((val, (desc, pol)) 
             for desc, val, pol in grouper(3, imap(str.rstrip, f)))


>>> d['00']
('this is ok', 'neutral')
>>> d['00'][0]
'this is ok'
>>> d['01'][0]
'this is good'

注意:在Python 3中使用普通map代码(不再需要导入),izip_longest现在是zip_longest