Mercurial > repos > stevecassidy > nltktools
comparison g_frequency.py @ 0:e991d4e60c17 draft
planemo upload commit 0203cb3a0b40d9348674b2b098af805e2986abca-dirty
author | stevecassidy |
---|---|
date | Wed, 12 Oct 2016 22:17:53 -0400 |
parents | |
children | fb617586f4b2 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:e991d4e60c17 |
---|---|
1 import nltk | |
2 from nltk import FreqDist | |
3 import argparse | |
4 | |
5 def arguments(): | |
6 parser = argparse.ArgumentParser(description="generate a word frequency table from a text") | |
7 parser.add_argument('--input', required=True, action="store", type=str, help="input text file") | |
8 parser.add_argument('--output', required=True, action="store", type=str, help="output file path") | |
9 args = parser.parse_args() | |
10 return args | |
11 | |
12 | |
13 def frequency(in_file, out_file): | |
14 """Input: a text file | |
15 Output: a table of word frequency with three columns for Word, Count and Percent frequency | |
16 """ | |
17 text = unicode(open(in_file, 'r').read(), errors='ignore') | |
18 words = nltk.word_tokenize(text) | |
19 frequency = FreqDist(words) | |
20 total = float(frequency.N()) | |
21 output = open(out_file, 'w') | |
22 output.write("Word\tCount\tPercent\n") | |
23 for pair in frequency.items(): | |
24 output.write("{pair[0]}\t{pair[1]}\t{pc:.2f}\n".format(pair=pair, pc=100*pair[1]/total)) | |
25 output.close() | |
26 | |
27 | |
28 if __name__ == '__main__': | |
29 args = arguments() | |
30 frequency(args.input, args.output) |