1

Switching dictionary to return values in python dictionaries instead of tuples

Former-commit-id: 3f0682e88a24faed24f9e12e7c9cee338e817672
This commit is contained in:
Alex Yatskov 2013-11-09 15:42:02 -08:00
parent 3b9ee50186
commit 4329d6c047
6 changed files with 74 additions and 60 deletions

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Copyright (C) 2011 Alex Yatskov # Copyright (C) 2013 Alex Yatskov
# #
# This program is free software: you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
@ -16,10 +16,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import deinflect
import dictionary
import os.path import os.path
from dictionary import Dictionary import translate
from deinflect import Deinflector
from translate import Translator
def buildRelPath(path): def buildRelPath(path):
@ -28,6 +28,7 @@ def buildRelPath(path):
def initLanguage(): def initLanguage():
deinflector = Deinflector(buildRelPath('data/deinflect.json')) return translate.Translator(
dictionary = Dictionary(buildRelPath('data/dictionary.db')) deinflect.Deinflector(buildRelPath('data/deinflect.json')),
return Translator(deinflector, dictionary) dictionary.Dictionary(buildRelPath('data/dictionary.db'))
)

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
# Copyright (C) 2011 Alex Yatskov # Copyright (C) 2013 Alex Yatskov
# #
# This program is free software: you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Copyright (C) 2011 Alex Yatskov # Copyright (C) 2013 Alex Yatskov
# #
# This program is free software: you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
@ -35,7 +35,12 @@ class Dictionary:
results = list() results = list()
for expression, reading, definitions, tags in cursor.fetchall(): for expression, reading, definitions, tags in cursor.fetchall():
results.append((expression, reading, definitions, tags.split())) results.append({
'expression': expression,
'reading': reading,
'definitions': definitions,
'tags': tags.split()
})
return results return results
@ -43,7 +48,16 @@ class Dictionary:
def findCharacter(self, character): def findCharacter(self, character):
cursor = self.db.cursor() cursor = self.db.cursor()
cursor.execute('SELECT * FROM Kanji WHERE character=? LIMIT 1', character) cursor.execute('SELECT * FROM Kanji WHERE character=? LIMIT 1', character)
return cursor.fetchone()
query = cursor.fetchone()
if query is not None:
character, kunyomi, onyomi, meanings = result
return {
'character': character,
'kunyomi': kunyomi,
'onyomi': onyomi,
'meanings': meanings
}
def findCharacterVisually(self, characters): def findCharacterVisually(self, characters):

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Copyright (C) 2011 Alex Yatskov # Copyright (C) 2013 Alex Yatskov
# This module is based on Rikaichan code written by Jonathan Zarate # This module is based on Rikaichan code written by Jonathan Zarate
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
@ -41,11 +41,11 @@ class Translator:
results = map(self.formatResult, groups.items()) results = map(self.formatResult, groups.items())
results = filter(operator.truth, results) results = filter(operator.truth, results)
results = sorted(results, key=lambda x: len(x[0]), reverse=True) results = sorted(results, key=lambda x: len(x['source']), reverse=True)
length = 0 length = 0
for expression, reading, definition, rules, source in results: for result in results:
length = max(length, len(source)) length = max(length, len(result['source']))
return results, length return results, length
@ -54,20 +54,21 @@ class Translator:
root = root or source root = root or source
for entry in self.dictionary.findTerm(root, partial): for entry in self.dictionary.findTerm(root, partial):
expression, reading, definition, tags = entry key = entry['expression'], entry['reading'], entry['definitions']
key = expression, reading, definition
if key not in groups: if key not in groups:
groups[key] = entry, source, rules groups[key] = entry, source, rules
def formatResult(self, group): def formatResult(self, group):
(expression, reading, definition), (entry, source, rules) = group (expression, reading, definition), (entry, source, rules) = group
return expression, reading, definition, rules, source return {
'expression': expression,
'reading': reading,
'definitions': definition,
'rules': rules,
'source': source
}
def validator(self, term): def validator(self, term):
results = list() return [d['tags'] for d in self.dictionary.findTerm(term)]
for expression, reading, definitions, tags in self.dictionary.findTerm(term):
results.append(tags)
return results

View File

@ -250,17 +250,17 @@ class MainWindowReader(QtGui.QMainWindow, reader_ui.Ui_MainWindowReader):
if command == 'addExpression': if command == 'addExpression':
markup = reader_util.buildFactMarkupExpression( markup = reader_util.buildFactMarkupExpression(
definition.expression, definition['expression'],
definition.reading, definition['reading'],
definition.glossary, definition['definitions'],
definition.sentence definition['sentence']
) )
self.ankiAddFact(markup) self.ankiAddFact(markup)
if command == 'addReading': if command == 'addReading':
markup = reader_util.buildFactMarkupReading( markup = reader_util.buildFactMarkupReading(
definition.reading, definition['reading'],
definition.glossary, definition['definitions'],
definition.sentence definition['sentence']
) )
self.ankiAddFact(markup) self.ankiAddFact(markup)
elif command == 'copyDefinition': elif command == 'copyDefinition':

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Copyright (C) 2011 Alex Yatskov # Copyright (C) 2013 Alex Yatskov
# #
# This program is free software: you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
@ -16,18 +16,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
from PyQt4 import QtGui from PyQt4 import QtGui
import re
class Definition:
def __init__(self, expression, reading, glossary, conjugations, source, sentence):
self.expression = expression
self.reading = reading
self.glossary = glossary
self.conjugations = conjugations
self.source = source
self.sentence = sentence
def decodeContent(content): def decodeContent(content):
@ -105,15 +95,21 @@ def replaceMarkupInFields(fields, markup):
return result return result
def buildFactMarkupExpression(expression, reading, glossary, sentence=None): def buildFactMarkupExpression(expression, reading, definitions, sentence=None):
return { return {
'%e': expression, '%r': reading, '%g': glossary, '%s': sentence '%e': expression,
'%r': reading,
'%g': definitions,
'%s': sentence
} }
def buildFactMarkupReading(reading, glossary, sentence=None): def buildFactMarkupReading(reading, definitions, sentence=None):
return { return {
'%e': reading, '%r': None, '%g': glossary, '%s': sentence '%e': reading,
'%r': None,
'%g': definitions,
'%s': sentence
} }
@ -122,38 +118,40 @@ def splitTags(tags):
def convertDefinitions(definitions, sentence=None): def convertDefinitions(definitions, sentence=None):
return [ if sentence is not None:
Definition(*(definition + (sentence,))) for definition in definitions for definition in definitions:
] definition['sentence'] = sentence
return definitions
def copyDefinitions(definitions): def copyDefinitions(definitions):
text = unicode() text = unicode()
for definition in definitions: for definition in definitions:
if definition.reading: if definition['reading']:
text += u'{0}\t{1}\t{2}\n'.format(definition.expression, definition.reading, definition.glossary) text += u'{expression}\t{reading}\t{definitions}\n'.format(**definition)
else: else:
text += u'{0}\t{1}\n'.format(definition.expression, definition.glossary) text += u'{expression}\t{meanings}\n'.format(**definition)
QtGui.QApplication.clipboard().setText(text) QtGui.QApplication.clipboard().setText(text)
def buildDefinitionHtml(definition, factIndex, factQuery): def buildDefinitionHtml(definition, factIndex, factQuery):
reading = unicode() reading = unicode()
if definition.reading: if definition['reading']:
reading = u'[{0}]'.format(definition.reading) reading = u'[{0}]'.format(definition['reading'])
conjugations = unicode() conjugations = unicode()
if len(definition.conjugations) > 0: if len(definition['rules']) > 0:
conjugations = u' :: '.join(definition.conjugations) conjugations = u' :: '.join(definition['rules'])
conjugations = '<span class = "conjugations">&lt;{0}&gt;<br/></span>'.format(conjugations) conjugations = '<span class = "conjugations">&lt;{0}&gt;<br/></span>'.format(conjugations)
links = '<a href = "copyDefinition:{0}"><img src = "://img/img/icon_copy_definition.png" align = "right"/></a>'.format(factIndex) links = '<a href = "copyDefinition:{0}"><img src = "://img/img/icon_copy_definition.png" align = "right"/></a>'.format(factIndex)
if factQuery: if factQuery:
if factQuery(buildFactMarkupExpression(definition.expression, definition.reading, definition.glossary)): if factQuery(buildFactMarkupExpression(definition['expression'], definition['reading'], definition['definitions'])):
links += '<a href = "addExpression:{0}"><img src = "://img/img/icon_add_expression.png" align = "right"/></a>'.format(factIndex) links += '<a href = "addExpression:{0}"><img src = "://img/img/icon_add_expression.png" align = "right"/></a>'.format(factIndex)
if factQuery(buildFactMarkupReading(definition.reading, definition.glossary)): if factQuery(buildFactMarkupReading(definition['reading'], definition['definitions'])):
links += '<a href = "addReading:{0}"><img src = "://img/img/icon_add_reading.png" align = "right"/></a>'.format(factIndex) links += '<a href = "addReading:{0}"><img src = "://img/img/icon_add_reading.png" align = "right"/></a>'.format(factIndex)
html = u""" html = u"""
@ -161,7 +159,7 @@ def buildDefinitionHtml(definition, factIndex, factQuery):
<span class = "expression">{1}&nbsp;{2}<br/></span> <span class = "expression">{1}&nbsp;{2}<br/></span>
<span class = "glossary">{3}<br/></span> <span class = "glossary">{3}<br/></span>
<span class = "conjugations">{4}</span> <span class = "conjugations">{4}</span>
<br clear = "all"/>""".format(links, definition.expression, reading, definition.glossary, conjugations) <br clear = "all"/>""".format(links, definition['expression'], reading, definition['definitions'], conjugations)
return html return html
@ -177,7 +175,7 @@ def buildDefinitionsHtml(definitions, factQuery):
span.expression {{ font-size: 15pt; }} span.expression {{ font-size: 15pt; }}
</style></head><body>""".format(toolTipBg, toolTipFg) </style></head><body>""".format(toolTipBg, toolTipFg)
if definitions: if len(definitions) > 0:
for i, definition in enumerate(definitions): for i, definition in enumerate(definitions):
html += buildDefinitionHtml(definition, i, factQuery) html += buildDefinitionHtml(definition, i, factQuery)
else: else: