1
yomichan-anki/yomi_base/japanese/translate.py

97 lines
2.9 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# Copyright (C) 2013 Alex Yatskov
# This module is based on Rikaichan code written by Jonathan Zarate
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
2016-05-29 23:18:07 +00:00
import re
class Translator:
def __init__(self, deinflector, dictionary):
self.deinflector = deinflector
2016-05-08 03:24:59 +00:00
self.dictionary = dictionary
def findTerm(self, text, wildcards=False):
2016-05-29 23:18:07 +00:00
if wildcards:
text = re.sub(u'[\*]', u'%', text)
text = re.sub(u'[\?]', u'_', text)
2016-05-09 21:33:52 +00:00
groups = {}
for i in xrange(len(text), 0, -1):
term = text[:i]
2016-05-09 21:33:52 +00:00
dfs = self.deinflector.deinflect(term, lambda term: [d['tags'] for d in self.dictionary.findTerm(term)])
if dfs is None:
continue
for df in dfs:
self.processTerm(groups, **df)
definitions = groups.values()
2016-05-18 03:31:40 +00:00
definitions = sorted(
definitions,
reverse=True,
key=lambda d: (
len(d['source']),
'P' in d['tags'],
-len(d['rules']),
d['expression']
)
)
length = 0
2016-05-09 21:33:52 +00:00
for result in definitions:
length = max(length, len(result['source']))
2016-05-09 21:33:52 +00:00
return definitions, length
2016-05-18 05:12:05 +00:00
def findKanji(self, text):
2016-05-08 03:24:59 +00:00
processed = {}
results = []
for c in text:
if c not in processed:
2016-05-09 21:33:52 +00:00
match = self.dictionary.findKanji(c)
if match is not None:
results.append(match)
processed[c] = match
return results
2016-05-09 21:33:52 +00:00
def processTerm(self, groups, source, tags, rules=[], root='', wildcards=False):
for entry in self.dictionary.findTerm(root, wildcards):
2016-05-09 21:33:52 +00:00
if entry['id'] in groups:
continue
matched = len(tags) == 0
for tag in tags:
if tag in entry['tags']:
matched = True
break
if matched:
groups[entry['id']] = {
'expression': entry['expression'],
'reading': entry['reading'],
'glossary': entry['glossary'],
'tags': entry['tags'],
'source': source,
'rules': rules
}