usr bin python coding utf-8 import os sys codecs def P1 P2 for in set

 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
#!/usr/bin/python
# coding: utf-8
import os, sys, codecs
def D(P1, P2):
s = 0
for x in set(P1.keys() + P2.keys()):
f1 = 0
if P1.has_key(x): f1 = P1[x]
f2 = 0
if P2.has_key(x): f2 = P2[x]
s += (2*(f1-f2) / (f1+f2)) ** 2
return s
def generate_profiles(list_of_documents):
list_of_files = [codecs.open(x, 'r') for x in list_of_documents]
list_of_profiles = []
#L = min(os.path.getsize(x) for x in list_of_documents)
print 'L ==', L
for f in list_of_files:
print f
text = f.read()
profile = {}
for i in xrange(L-N+1):
if (i % 10000) == 0: print "i = %s" % i
gram = text[i:i+N].lower()
if gram in profile.keys():
profile[gram] += 1
else:
profile[gram] = 1
list_of_profiles.append(profile)
return list_of_profiles
def check(list_of_documents):
profiles = generate_profiles(list_of_documents)
r = []
u = profiles[0]
# пусть первый документ - это образец
for d_i in profiles[1:]:
r.append(float(D(d_i, u)) / max(D(d_i, x) for x in profiles[1:]))
M = float(sum(r))/len(r)
if M > 1:
return False
else:
return True
N = 3
L = 30000
print check(['Korpusa/r1.txt', 'Korpusa/r2.txt', 'Korpusa/r3.txt', 'Korpusa/r4.txt'])