Last active
March 8, 2016 14:42
-
-
Save dboyliao/f50ee9638e945c95f28a to your computer and use it in GitHub Desktop.
Count Matched Pattern in The File
This file contains hidden or 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
| #!/usr/bin/env python | |
| # Simple counting program | |
| from __future__ import print_function | |
| import re | |
| import argparse | |
| def count_pattern(fname, pattern): | |
| count = 0 | |
| pattern = re.compile(pattern) | |
| with open(fname) as rf: | |
| l = rf.readline() | |
| while not l == "": | |
| match = pattern.findall(l) | |
| count += len(match) | |
| l = rf.readline() | |
| return count | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description = "count the number of matched pattern in the file.") | |
| parser.add_argument("fname", metavar = "FILE", help = "file name") | |
| parser.add_argument("-e", "--pattern", metavar = "PATTERN", default = "[^\s]", | |
| help = "regular expression pattern", dest = "pattern") | |
| args = parser.parse_args() | |
| count = count_pattern(args.fname, args.pattern) | |
| print(count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment