-1

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

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

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

4

1 回答 1

0

使用grouper配方 fromitertools以 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 中使用 normalmap代替(不再需要导入)并且izip_longest现在zip_longest

于 2013-04-15T06:30:26.610 回答