0

Here is my input text file with three fields. (description, value, polarity)

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

So i need to get all descriptions based on the value field. For Ex: I want to print "This is good" when i check the if condition for "01". Is there any way to do it. Please suggest me.

jamylak
  • 128,818
  • 30
  • 231
  • 230
Vittal Cherala
  • 447
  • 1
  • 6
  • 14
  • Visit http://stackoverflow.com/questions/9073699/cant-print-a-specific-line-from-text-file possibly duplicate question.. –  Apr 15 '13 at 06:13
  • Thanks for your reply, I have verified that link, in that text file. Text is separated with ':' but my text file is diffrent. but i tried that code it doesn't work for my requirement. – Vittal Cherala Apr 15 '13 at 06:20
  • [DUPLICATE](http://stackoverflow.com/questions/16009161/how-do-i-use-a-specific-line-of-a-text-file-in-python) – Dharmjeet Kumar Apr 15 '13 at 06:45

1 Answers1

0

Using the grouper recipe from itertools to iterate through the file in chunks of 3 lines:

>>> 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'

Notes: In Python 3 use normal map instead (which no longer requires an import) and izip_longest is now zip_longest

jamylak
  • 128,818
  • 30
  • 231
  • 230
  • Thanks, but i am getting the following error " d = {val: (desc, pol) for desc, val, pol in grouper(3, imap(str.rstrip, f))} ^ SyntaxError: invalid syntax" – Vittal Cherala Apr 15 '13 at 06:45
  • @VittalCherala Oh are you on Python <=2.6? Updated now – jamylak Apr 15 '13 at 06:47
  • @VittalCherala Just in case you misinterpreted me, I updated my code to be compatible with Py 2.6, you don't have to update your Python although it would be a good idea ;) – jamylak Apr 15 '13 at 07:30