1 """Language-specific functions, including models of languages based on data of
11 from math
import log10
14 """Remove all non-alphabetic characters from a text
15 >>> letters('The Quick')
17 >>> letters('The Quick BROWN fox jumped! over... the (9lazy) DOG')
18 'TheQuickBROWNfoxjumpedoverthelazyDOG'
20 return ''.join([c
for c
in text
if c
in string
.ascii_letters
])
23 """Remove all accents from letters.
24 It does this by converting the unicode string to decomposed compatability
25 form, dropping all the combining accents, then re-encoding the bytes.
38 return unicodedata
.normalize('NFKD', text
).\
39 encode('ascii', 'ignore').\
43 """Remove all non-alphabetic characters and convert the text to lowercase
45 >>> sanitise('The Quick')
47 >>> sanitise('The Quick BROWN fox jumped! over... the (9lazy) DOG')
48 'thequickbrownfoxjumpedoverthelazydog'
52 # sanitised = [c.lower() for c in text if c in string.ascii_letters]
53 # return ''.join(sanitised)
54 return letters(unaccent(text
)).lower()
57 def datafile(name
, sep
='\t'):
58 """Read key,value pairs from file.
60 with
open(name
, 'r') as f
:
62 splits
= line
.split(sep
)
63 yield [splits
[0], int(splits
[1])]
65 english_counts
= collections
.Counter(dict(datafile('count_1l.txt')))
66 normalised_english_counts
= norms
.normalise(english_counts
)
68 with
open('words.txt', 'r') as f
:
69 keywords
= [line
.rstrip() for line
in f
]
72 def weighted_choice(d
):
73 """Generate random item from a dictionary of item counts
75 target
= random
.uniform(0, sum(d
.values()))
77 for (l
, p
) in d
.items():
83 def random_english_letter():
84 """Generate a random letter based on English letter counts
86 return weighted_choice(normalised_english_counts
)
90 """A probability distribution estimated from counts in datafile.
91 Values are stored and returned as log probabilities.
93 def __init__(self
, data
=[], estimate_of_missing
=None):
94 data1
, data2
= itertools
.tee(data
)
95 self
.total
= sum([d
[1] for d
in data1
])
96 for key
, count
in data2
:
97 self
[key
] = log10(count
/ self
.total
)
98 self
.estimate_of_missing
= estimate_of_missing
or (lambda k
, N
: 1./N
)
99 def __missing__(self
, key
):
100 return self
.estimate_of_missing(key
, self
.total
)
102 def log_probability_of_unknown_word(key
, N
):
103 """Estimate the probability of an unknown word.
105 return -log10(N
* 10**((len(key
) - 2) * 1.4))
107 Pw
= Pdist(datafile('count_1w.txt'), log_probability_of_unknown_word
)
108 Pw_wrong
= Pdist(datafile('count_1w.txt'), lambda _k
, N
: log10(1/N
))
109 Pl
= Pdist(datafile('count_1l.txt'), lambda _k
, _N
: 0)
110 P2l
= Pdist(datafile('count_2l.txt'), lambda _k
, _N
: 0)
111 P3l
= Pdist(datafile('count_3l.txt'), lambda _k
, _N
: 0)
114 """The Naive Bayes log probability of a sequence of words.
116 return sum(Pw
[w
.lower()] for w
in words
)
118 def Pwords_wrong(words
):
119 """The Naive Bayes log probability of a sequence of words.
121 return sum(Pw_wrong
[w
.lower()] for w
in words
)
123 def Pletters(letters
):
124 """The Naive Bayes log probability of a sequence of letters.
126 return sum(Pl
[l
.lower()] for l
in letters
)
129 def cosine_similarity_score(text
):
130 """Finds the dissimilarity of a text to English, using the cosine distance
131 of the frequency distribution.
133 >>> cosine_similarity_score('abcabc') # doctest: +ELLIPSIS
136 return norms
.cosine_similarity(english_counts
,
137 collections
.Counter(sanitise(text
)))
140 if __name__
== "__main__":