textfile: copy between 2 keywords
Vlastimil Brom
vlastimil.brom at gmail.com
Thu Sep 10 10:33:37 EDT 2015
2015-09-10 13:18 GMT+02:00 Gerald <schweiger.gerald at gmail.com>:
> 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
>
>
> Thank you very much
Hi,
just to add another possible approach, you can use regular expression
search for this task, e.g.
(after you have read the text content to an input string):
>>> import re
>>> input_txt ="""1, 2, 3, 4
... #keyword1
... 3, 4, 5, 6
... 2, 3, 4, 5
... #keyword2
... 4, 5, 6 ,7"""
>>> re.findall(r"(?s)(#keyword1)(.*?)(#keyword2)", input_txt)
[('#keyword1', '\n3, 4, 5, 6\n2, 3, 4, 5\n', '#keyword2')]
>>>
like in the other approaches, you might need to specify the details
for specific cases (no keywords, only one of them, repeated keywords
(possible in different order, overlapping or "crossed"), handling of
newlines etc.
hth,
vbr
More information about the Python-list
mailing list