forked from nahuelhds/simple-text-analysis-nlp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
count.py
65 lines (53 loc) · 1.75 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
#!/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, outputfilename, rank=False):
# get data directory (using getcwd() is needed to support running example in generated IPython notebook)
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
# Read the whole text.
text = open(path.join(d, "output", inputfilename)).read().split(' ')
words = nltk.FreqDist(text)
if(rank == False):
words = sorted(words.items())
else:
words = words.most_common()
outputfile = open(path.join(d, "wordcount", outputfilename), "w+")
outputfile.write("WORD,COUNT\n")
with outputfile as outputfile:
for word, count in words:
outputfile.write("%s,%d\n" % (word, count))
def main(argv):
input = ''
output = ''
rank = False
try:
opts, args = getopt.getopt(argv, "hi:o:r", [
"input=",
"output=",
"rank"
])
except getopt.GetoptError:
print('test.py -i <inputfile>')
sys.exit(2)
if len(opts) < 1:
print('test.py -i <inputfile>')
else:
for opt, arg in opts:
if opt == '-h':
print('test.py -i <inputfile>')
sys.exit()
elif opt in ("-i", "--input"):
input = arg.strip()
elif opt in ("-o", "--output"):
output = arg.strip()
elif opt in ('-r', '--rank'):
rank = True
print(wordCount(input, output, rank))
if __name__ == "__main__":
main(sys.argv[1:])