Last active
February 1, 2017 19:20
-
-
Save artificialsoph/c812c5a1c37e697b93c8ac719fe87849 to your computer and use it in GitHub Desktop.
Pattern Matching
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
target | |
+ | |
+ | |
+ | |
+ | |
blah | |
+ | |
+ | |
+ | |
+ | |
+ | |
+ | |
target | |
+ | |
+ | |
+ | |
+ | |
blah | |
+ | |
+ | |
+ | |
target | |
+ | |
+ | |
+ | |
+ | |
blah |
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
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) |
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
blah | |
+ | |
+ | |
+ | |
+ | |
+ | |
+ | |
+ | |
+ | |
+ | |
+ | |
+ | |
blah | |
+ | |
+ | |
+ | |
+ | |
+ | |
+ | |
+ | |
+ | |
blah | |
+ | |
+ | |
+ | |
+ | |
+ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment