-
Notifications
You must be signed in to change notification settings - Fork 1
/
mapper2.py
68 lines (55 loc) · 1.87 KB
/
mapper2.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
#!/usr/bin/python2.7
import sys
import re
import io
import codecs
sys.stdin = codecs.getreader("utf-8")(sys.stdin)
def make_ngrams(plain_text, n, split = lambda x: list ( x ) ):
ngram_array = []
array_text = split ( plain_text )
for i in range(len(array_text) - n + 1):
ngram = []
#ngram = ""
for j in range(i, i + n):
#ngram = ngram + array_text [j]
ngram.append((array_text[j]))
ngram_array.append(tuple(ngram))
#ngram_array.append(ngram)
return ngram_array
def counter(ngram_array):
def item_get(array, key):
if key in array.keys():
return array[key]
else:
return 0
if sys.version_info < (2, 7):
# compatibility
map = {}
if ngram_array is not None:
if hasattr(ngram_array, "iteritems"):
for elem, count in ngram_array.iteritems():
map[elem] = item_get(map, elem) + count
else:
for elem in ngram_array:
map[elem] = item_get(map, elem) + 1
return map
else:
import collections
return collections.Counter(ngram_array)
def count_ngrams(plain_text, n, split = lambda x: list ( x ) ):
ngram_array = make_ngrams(plain_text, n, split)
ngrams = counter(ngram_array)
return ngrams
for line in sys.stdin:
#line = line.strip() # remove leading and trailing whitespace
line = re . sub ( "\r", "\n", line )
line = re . sub ( "\n\n", "\n", line )
#
#
# if we use count_ngrams ( line, 1, lambda x: x . split () )
# we are making ngrams from whole words
# By default is using lambda x: list ( x ) which splits string to characters
#
ngrams = count_ngrams( line, 2 );
for elem in ngrams.keys():
print ( '%s\t%s' % ( str ( elem ) . encode ( "utf-8" ), ngrams[elem] ) )