38 lines
1.3 KiB
Python
38 lines
1.3 KiB
Python
|
import logging
|
||
|
from utils.file_utils import read_json, write_json
|
||
|
|
||
|
|
||
|
class WordDictionary:
|
||
|
def __init__(self, dictionary=None, file_path='config/word_dictionary.json'):
|
||
|
"""WordDictionaryクラスの初期化を行う"""
|
||
|
self.dictionary = dictionary if dictionary else {}
|
||
|
self.file_path = file_path
|
||
|
self.load_from_json()
|
||
|
|
||
|
def register_word(self, word, reading):
|
||
|
"""単語を辞書に登録する"""
|
||
|
self.dictionary[word] = reading
|
||
|
self.save_to_json()
|
||
|
|
||
|
def convert_text(self, text):
|
||
|
"""テキスト内の単語を辞書を使って変換する"""
|
||
|
for word in sorted(self.dictionary, key=len, reverse=True):
|
||
|
reading = self.dictionary[word]
|
||
|
text = text.replace(word, reading)
|
||
|
return text
|
||
|
|
||
|
def save_to_json(self):
|
||
|
"""辞書をJSONファイルに保存する"""
|
||
|
write_json(self.dictionary, self.file_path)
|
||
|
|
||
|
def load_from_json(self):
|
||
|
"""JSONファイルから辞書を読み込む"""
|
||
|
try:
|
||
|
self.dictionary = read_json(self.file_path)
|
||
|
except FileNotFoundError:
|
||
|
write_json({}, self.file_path)
|
||
|
self.dictionary = {}
|
||
|
except Exception as e:
|
||
|
logging.info(f"Failed to load dictionary from JSON: {e}")
|
||
|
raise Exception(f"Failed to load dictionary from JSON: {e}")
|