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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
#!/usr/bin/python3
import os
import sqlite3
from argparse import ArgumentParser
from operator import itemgetter
import utils
from myconfig import MyConfig
from dirwalk import walkIndex
SELECT_WORD_DML = '''
SELECT freq from ngram where words = ?;
'''
config = MyConfig()
#change cwd to the word recognizer directory
words_dir = config.getWordRecognizerDir()
os.chdir(words_dir)
#chdir done
def getWordFrequency(conn, word):
sep = config.getWordSep()
word_str = sep + word + sep
cur = conn.cursor()
row = cur.execute(SELECT_WORD_DML, (word_str, )).fetchone()
if None == row:
return 0
else:
freq = row[0]
return freq
def computeThreshold(conn):
wordswithfreq = []
wordlistfile = open(config.getWordsListFileName(), "r")
for oneline in wordlistfile.readlines():
oneline = oneline.rstrip(os.linesep)
if len(oneline) == 0:
continue
word = oneline
freq = getWordFrequency(conn, word)
if freq < config.getMinimumOccurrence():
continue
wordswithfreq.append((word, freq))
wordlistfile.close()
#ascending sort
wordswithfreq.sort(key=itemgetter(1))
pos = int(len(wordswithfreq) * config.getPartialWordThreshold())
(word, threshold) = wordswithfreq[-pos]
print(word, threshold)
return threshold
def handleOneIndex(indexpath, subdir, indexname):
print(indexpath, subdir, indexname)
indexstatuspath = indexpath + config.getStatusPostfix()
indexstatus = utils.load_status(indexstatuspath)
if not utils.check_epoch(indexstatus, 'Populate'):
raise utils.EpochError('Please populate first.\n')
if utils.check_epoch(indexstatus, 'PartialWordThreshold'):
return
workdir = config.getWordRecognizerDir() + os.sep + \
subdir + os.sep + indexname
print(workdir)
length = 1
filename = config.getNgramFileName(length)
filepath = workdir + os.sep + filename
conn = sqlite3.connect(filepath)
threshold = computeThreshold(conn)
indexstatus['PartialWordThreshold'] = threshold
conn.commit()
if conn:
conn.close()
#sign epoch
utils.sign_epoch(indexstatus, 'PartialWordThreshold')
utils.store_status(indexstatuspath, indexstatus)
if __name__ == '__main__':
parser = ArgumentParser(description='Partial word threshold.')
parser.add_argument('--indexdir', action = 'store', \
help='index directory', \
default=config.getTextIndexDir())
args = parser.parse_args()
print(args)
walkIndex(handleOneIndex, args.indexdir)
print('done')
|