Skip to content

Instantly share code, notes, and snippets.

@artificialsoph
Last active February 1, 2017 19:20
Show Gist options
  • Save artificialsoph/c812c5a1c37e697b93c8ac719fe87849 to your computer and use it in GitHub Desktop.
Save artificialsoph/c812c5a1c37e697b93c8ac719fe87849 to your computer and use it in GitHub Desktop.
Pattern Matching
target
+
+
+
+
blah
+
+
+
+
+
+
target
+
+
+
+
blah
+
+
+
target
+
+
+
+
blah
f = open("input.txt", "r") # open input file
file_text = f.read() # read all text from file
file_lines = file_text.split("\n") # split the text by line
match_indices = [] # indices for pattern matches
match_pattern = "blah"
target_pattern = "target"
i = 0
while i < len(file_lines):
current_line = file_lines[i]
if current_line == match_pattern:
# This version *replaces* "target" with "blah"
if file_lines[i-5] == target_pattern:
file_lines[i-5] = file_lines[i]
file_lines[i] = "+"
i = i+1
# this version *inserts* blah (assuming the file doesn't contain "target")
# file_lines.input(i-5,file_lines[i])
# file_lines[i+1] = "+"
i = i+1
new_file_text = "\n".join(file_lines)
f.close()
f = open("output.txt","r+")
f.write(new_file_text)
blah
+
+
+
+
+
+
+
+
+
+
+
blah
+
+
+
+
+
+
+
+
blah
+
+
+
+
+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment