python - Turning a text file with words and their positions into a sentence -


say had text file comments, , keys , values so:

# following # list of words , positions i: 1 like: 2 to: 3, 5 go: 4 cafes: 6 

how go turning sentence ('i go cafes')? supposed should try turn text dictionary first, having trouble removing comments , splitting keys , values... great!

read file, appending word , positions tuples list. sort list, remove indices , join words:

with open(inputfilename) inputfile:     words = []     line in inputfile:         line = line.strip()         if not line or line.startswith('#'):             continue         word, positions = line.split(':')         words.extend((int(p), word) p in positions.split(','))  print ' '.join([w p, w in sorted(words)]) 

demo:

>>> open(inputfilename) inputfile: ...     words = [] ...     line in inputfile: ...         line = line.strip() ...         if not line or line.startswith('#'): ...             continue ...         word, positions = line.split(':') ...         words.extend((int(p), word) p in positions.split(',')) ...  >>> print ' '.join([w p, w in sorted(words)]) go cafes 

Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -