Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #96258

Re: textfile: copy between 2 keywords

From Jussi Piitulainen <harvesting@makes.email.invalid>
Newsgroups comp.lang.python
Subject Re: textfile: copy between 2 keywords
Date 2015-09-10 16:47 +0300
Organization A noiseless patient Spider
Message-ID <lf57fnyo078.fsf@ling.helsinki.fi> (permalink)
References <13d875f0-ae8d-43de-85b4-c943a0e7f5e2@googlegroups.com>

Show all headers | View raw


Gerald writes:

> Hey,
>
> is there a easy way to copy the content between 2 unique keywords in a
> .txt file?
>
> example.txt
>
> 1, 2, 3, 4
> #keyword1
> 3, 4, 5, 6
> 2, 3, 4, 5
> #keyword2 
> 4, 5, 6 ,7

Depending on your notion of easy, you may or may not like itertools.
The following code gets you the first keyword and the lines between but
consumes the second keyword. If I needed more control, I'd probably
write what Steven D'Aprano wrote but as a generator function, to get the
flexibility of deciding separately what kind of copy I want in the end.

And I'd be anxious about the possibility that the second keyword is not
there in the input at all. Steven's code and mine simply take every line
after the first keyword in that case. Worth a comment in the code, if
not an exception. Depends.

Code:

from itertools import dropwhile, takewhile
from sys import stdin

def notbeg(line): return line != '#keyword1\n'
def notend(line): return line != '#keyword2 \n' # sic!

if __name__ == '__main__':
    print(list(takewhile(notend, dropwhile(notbeg, stdin))))

Output with your original mail as input in stdin:

['#keyword1\n', '3, 4, 5, 6\n', '2, 3, 4, 5\n']

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

textfile: copy between 2 keywords Gerald <schweiger.gerald@gmail.com> - 2015-09-10 04:18 -0700
  Re: textfile: copy between 2 keywords Steven D'Aprano <steve@pearwood.info> - 2015-09-10 22:10 +1000
  Re: textfile: copy between 2 keywords Jussi Piitulainen <harvesting@makes.email.invalid> - 2015-09-10 16:47 +0300
  Re: textfile: copy between 2 keywords Vlastimil Brom <vlastimil.brom@gmail.com> - 2015-09-10 16:33 +0200
    Re: textfile: copy between 2 keywords Jussi Piitulainen <harvesting@makes.email.invalid> - 2015-09-10 18:48 +0300
  Re: textfile: copy between 2 keywords Christian Gollwitzer <auriocus@gmx.de> - 2015-09-10 19:29 +0200
    Re: textfile: copy between 2 keywords wxjmfauth@gmail.com - 2015-09-10 12:11 -0700
      Re: textfile: copy between 2 keywords alister <alister.nospam.ware@ntlworld.com> - 2015-09-10 19:41 +0000

csiph-web