Created
February 12, 2022 18:17
-
-
Save akarca/ba76c30191292b9cfeaddd4d5601dc26 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def grep(text, match, after=0, before=0): | |
""" | |
Return matched lines in given text as a list. Similar to grep function but a simple one. | |
""" | |
idx = [] | |
lines = text.split("\n") | |
for i, line in enumerate(lines): | |
if str(match) not in line: | |
continue | |
idx.append(i) | |
if after: | |
idx += range(i + 1, i + 1 + after) | |
if before: | |
idx += range(i - before, i) | |
idx = sorted(list(set(idx))) | |
return [lines[i] for i in idx] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment