OSDN Git Service

new classify function added.
[rec10/rec10-git.git] / rec10 / trunk / src / n_gram.py
1 #!/usr/bin/python
2 # coding: UTF-8
3 # Rec10 TS Recording Tools
4 # Copyright (C) 2009 Yukikaze
5
6 import zenhan
7 def bigram(str1, str2):
8     str1 = zenhan.toHankaku(str1)
9     str2 = zenhan.toHankaku(str2)
10     str1 = str1.replace(" ", "")
11     str2 = str2.replace(" ", "")
12     """
13     bigramによる単語の近さを計算します。
14     """
15     gram = []
16     if len(str1) < 2:
17         gram.append(str1)
18     else:
19         tmp = str1[0]
20         for x in str1[1:]:
21             gram.append(tmp + x)
22             tmp = x
23     point = 0
24     for x in gram:
25         i = find_gram(x, str2)
26         if i > 0:
27             i = 90 + 10 * i
28         else:
29             i = 0
30         point = point + i
31     return point
32 def trigram(str1, str2):
33     str1 = zenhan.toHankaku(str1)
34     str2 = zenhan.toHankaku(str2)
35     str1 = str1.replace(" ", "")
36     str2 = str2.replace(" ", "")
37     """
38     trigramによる単語の近さを計算します。
39     """
40     gram = []
41     if len(str1) < 3:
42         gram.append(str1)
43     else:
44         tmp1 = str1[0]
45         tmp2 = str1[1]
46         for x in str1[2:]:
47             gram.append(tmp1 + tmp2 + x)
48             tmp1 = tmp2
49             tmp2 = x
50     point = 0
51     for x in gram:
52         i = find_gram(x, str2)
53         if i > 0:
54             i = 90 + 10 * i
55         else:
56             i = 0
57         point = point + i
58     return point
59 def find_gram(gram, s):
60     """
61     s中にあらわれるgramの数を調べる
62     """
63     st = s
64     i = 0
65     while st.find(gram) != -1:
66         i = i + 1
67         st = st[st.find(gram) + 1:]
68     return i
69 ""