Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import sys, os
- class WC :
- """"word count class"""
- def getWords(self, data):
- noise = ['\n', '\t', ',', '.', ';', ':', '-', '!', '?', '*', '(', ')', '{', '}', '[', ']', '|']
- for char in noise :
- data = data.replace(char, ' ')
- return data.split()
- def words(self, data) :
- return len(self.getWords(data))
- def strings(self, data) :
- return len(data.split('\n')) - 1
- def wordsDuplicates(self, data) :
- unique = {}
- for word in self.getWords(data) :
- if word in unique :
- unique[word] += 1
- else :
- unique[word] = 1
- return unique
- def bytes(self, data) :
- return sys.getsizeof(data)
- keysAvailable = {
- "-l": 'strings',
- "-w": "words",
- "-W": "wordsDuplicates",
- "-b": "bytes"
- }
- arguments = sys.argv
- arguments.pop(0)
- keys = list(filter((lambda x: x.startswith("-")), sys.argv))
- args = list(filter((lambda x: not x.startswith("-")), sys.argv))
- if (len(args) != 1 ) :
- sys.exit("invalid arguments count");
- filename = args[0]
- if (os.path.exists(filename)) :
- try :
- with open(filename, 'r') as fo :
- data = fo.read()
- except IOError :
- sys.exit("Could not read file " + filename)
- finally :
- fo.close()
- else :
- sys.exit("No such file " + filename)
- wc = WC()
- for key in keys :
- if key in keysAvailable :
- method = getattr(wc, keysAvailable.get(key))
- result = method(data)
- print(keysAvailable.get(key) + ': ' + str(result))
Add Comment
Please, Sign In to add comment