Skip to content

Commit d8cd429

Browse files
committed
Add word-counter.py
1 parent eac1e29 commit d8cd429

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

python3/word-counter.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#!/usr/bin/env python3
2+
3+
from collections import Counter
4+
import argparse
5+
import re
6+
from itertools import islice
7+
import operator
8+
9+
parser = argparse.ArgumentParser()
10+
parser.add_argument('--numWords',type=int,default=10)
11+
parser.add_argument('--maxTuples',type=int,default=4)
12+
parser.add_argument('--minWordLength',type=int,default=5)
13+
parser.add_argument('file',type=str)
14+
args = parser.parse_args()
15+
16+
# Inspired by http://stackoverflow.com/questions/6822725
17+
def window(seq, n):
18+
it = iter(seq)
19+
result = tuple(islice(it, n))
20+
if len(result) == n:
21+
yield result
22+
for elem in it:
23+
result = result[1:] + (elem,)
24+
containsShortWord = False
25+
for i in result:
26+
if len(i) < args.minWordLength:
27+
containsShortWord = True
28+
break
29+
if not containsShortWord:
30+
yield result
31+
32+
with open(args.file,'r') as f:
33+
content = f.read().replace('\n',' ')
34+
words = re.findall(r'\S+', content)
35+
for i in range(1,args.maxTuples+1):
36+
print("\n=== Sliding Window: {} ===".format(i))
37+
for tup in Counter(window(words,i)).most_common(args.numWords):
38+
print(" {}: '{}'".format(tup[1]," ".join(tup[0])))

0 commit comments

Comments
 (0)