-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcount.py
75 lines (59 loc) · 1.77 KB
/
count.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/python3
import os
import sys
import getopt
import nltk
from os import path
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
dir = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
def wordCount(inputfilename, rank=False):
# Read the whole text.
text = open(path.join(dir, inputfilename)).read().split(' ')
words = nltk.FreqDist(text)
if(rank == False):
words = sorted(words.items())
else:
words = words.most_common()
basename = path.basename(path.splitext(inputfilename)[0])
if(rank is True):
filename = "count-rank.txt"
else:
filename = "count.txt"
outputfilename = path.join(dir, "output", basename, filename)
outputfolder = os.path.dirname(outputfilename)
if not os.path.exists(outputfolder):
os.makedirs(outputfolder)
outputfile = open(path.join(dir, outputfilename), "w+")
outputfile.write("WORD,COUNT\n")
with outputfile as outputfile:
for word, count in words:
outputfile.write("%s,%d\n" % (word, count))
def printCmd():
print('count.py -i <inputfile> --rank')
def main(argv):
input = ''
rank = False
try:
opts, args = getopt.getopt(argv, "hi:r", [
"input=",
"rank"
])
except getopt.GetoptError:
printCmd()
sys.exit(2)
if len(opts) < 1:
printCmd()
sys.exit()
else:
for opt, arg in opts:
if opt == '-h':
printCmd()
sys.exit()
elif opt in ("-i", "--input"):
input = arg.strip()
elif opt in ('-r', '--rank'):
rank = True
wordCount(input, rank)
if __name__ == "__main__":
main(sys.argv[1:])