Last active
December 12, 2015 04:39
-
-
Save jadudm/4716053 to your computer and use it in GitHub Desktop.
For a demo in class.
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
import sys | |
import re | |
# Note: In a language without types, it is good practice to | |
# annotate your functions with a type contract. For example, | |
# "find_matches" takes two strings and has no return value. | |
# Writing a purpose statement indicates you know what you are trying | |
# to do, and makes it easier for other people to read your code. | |
# CONTRACT | |
# find_matches : string string -> void | |
# PURPOSE | |
# Consumes two strings, and has no return value. | |
# Takes a regular expression pattern and a filename. | |
# find_matches goes through every line of the file, looking for | |
# matches, and prints out lines matching the pattern provided. | |
def find_matches (pattern, file): | |
f = open (file, 'r') | |
for line in f: | |
if re.match(pattern, line): | |
print line | |
f.close() | |
# CONTRACT | |
# main : void -> void | |
# PURPOSE | |
# Run when the script is executed | |
def main(): | |
if len(sys.argv) < 3: | |
print "I need a file to mangle!" | |
sys.exit(-1) | |
pat = sys.argv[1] | |
file = sys.argv[2] | |
print "Searching in the file %s for the word %s" % (file, pat) | |
find_matches(pat, file) | |
# This is the "Python-y" way to indicate which function | |
# to run first. | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment