Commit
·
d022753
1
Parent(s):
f3802e8
Upload ZEN/ngram_utils.py
Browse files- ZEN/ngram_utils.py +53 -0
ZEN/ngram_utils.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
# Copyright 2019 Sinovation Ventures AI Institute
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""utils for ngram for ZEN model."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import logging
|
| 19 |
+
|
| 20 |
+
NGRAM_DICT_NAME = 'ngram.txt'
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
class ZenNgramDict(object):
|
| 25 |
+
"""
|
| 26 |
+
Dict class to store the ngram
|
| 27 |
+
"""
|
| 28 |
+
def __init__(self, ngram_freq_path, tokenizer, max_ngram_in_seq=128):
|
| 29 |
+
"""Constructs ZenNgramDict
|
| 30 |
+
|
| 31 |
+
:param ngram_freq_path: ngrams with frequency
|
| 32 |
+
"""
|
| 33 |
+
if os.path.isdir(ngram_freq_path):
|
| 34 |
+
ngram_freq_path = os.path.join(ngram_freq_path, NGRAM_DICT_NAME)
|
| 35 |
+
self.ngram_freq_path = ngram_freq_path
|
| 36 |
+
self.max_ngram_in_seq = max_ngram_in_seq
|
| 37 |
+
self.id_to_ngram_list = ["[pad]"]
|
| 38 |
+
self.ngram_to_id_dict = {"[pad]": 0}
|
| 39 |
+
self.ngram_to_freq_dict = {}
|
| 40 |
+
|
| 41 |
+
logger.info("loading ngram frequency file {}".format(ngram_freq_path))
|
| 42 |
+
with open(ngram_freq_path, "r", encoding="utf-8") as fin:
|
| 43 |
+
for i, line in enumerate(fin):
|
| 44 |
+
ngram,freq = line.split(",")
|
| 45 |
+
tokens = tuple(tokenizer.tokenize(ngram))
|
| 46 |
+
self.ngram_to_freq_dict[ngram] = freq
|
| 47 |
+
self.id_to_ngram_list.append(tokens)
|
| 48 |
+
self.ngram_to_id_dict[tokens] = i + 1
|
| 49 |
+
|
| 50 |
+
def save(self, ngram_freq_path):
|
| 51 |
+
with open(ngram_freq_path, "w", encoding="utf-8") as fout:
|
| 52 |
+
for ngram,freq in self.ngram_to_freq_dict.items():
|
| 53 |
+
fout.write("{},{}\n".format(ngram, freq))
|