se_eng_fr_dict = {'School': ['Skola', 'Ecole'], 'Ball': ['Boll', 'Ballon']}
choose_language = raw_input("Type 'English', for English. Skriv 'svenska' fo:r svenska. Pour francais, ecrit 'francais'. ")
if choose_language == 'English':
word = raw_input("Type in a word:")
swe_word = se_eng_fr_dict[word][0]
fra_word = se_eng_fr_dict[word][1]
print word, ":", swe_word, "pa. svenska," , fra_word, "en francais."
elif choose_language == 'Svenska':
word = raw_input("Vilket ord:")
for key, value in se_eng_fr_dict.iteritems():
if value == word:
print key
我想创建一个字典(在本地存储为txt文件),用户可以选择输入英语,瑞典语或法语单词,以便用其他两种语言翻译单词。用户还应该能够将数据添加到字典中。
当我用英文单词查找瑞典语和法语单词时,代码有效。但是,如果我只有value1,我如何获得Key和Value2? 有没有办法或者我应该尝试以不同的方式解决这个问题?
答案 0 :(得分:0)
如果尚未设置值,则可以选择存储None
。虽然它会增加所需的内存量,但您可以更进一步添加语言本身。
示例:
se_eng_fr_dict = {'pencil': {'se': None, 'fr': 'crayon'}}
def translate(word, lang):
# If dict.get() finds no value with `word` it will return
# None by default. We override it with an empty dictionary `{}`
# so we can always call `.get` on the result.
translated = se_eng_fr_dict.get(word, {}).get(lang)
if translated is None:
print("No {lang} translation found for {word}.format(**locals()))
else:
print("{} is {} in {}".format(word, translated, lang))
translate('pencil', 'fr')
translate('pencil', 'se')
答案 1 :(得分:0)
也许一组嵌套列表会更好:
>>> my_list = [
[
"School", "Skola", "Ecole"
],
[
"Ball", "Boll", "Ballon"
]
]
然后您可以通过执行以下操作来访问这组翻译:
>>> position = [index for index, item in enumerate(my_list) for subitem in item if value == subitem][0]
这将返回列表的索引,您可以抓取:
>>> sub_list = my_list[position]
子列表将按顺序包含所有翻译。
例如:
>>> position = [index for index, item in enumerate(my_list) for subitem in item if "Ball" == subitem][0]
>>> print position
1
>>> my_list[position]
['Ball', 'Boll', 'Ballon']
答案 2 :(得分:0)
我希望有更好的解决方案,但这是我的:
class Word:
def __init__(self, en, fr, se):
self.en = en
self.fr = fr
self.se = se
def __str__(self):
return '<%s,%s,%s>' % (self.en, self.fr, self.se)
然后将所有这些Word
转储到映射数据结构中。你可以使用字典,但如果你有一个庞大的数据集,你最好使用BST,看看https://pypi.python.org/pypi/bintrees/2.0.1
假设您已将所有这些Word
加载到名为words
的列表中,然后:
en_words = {w.en: w for w in words}
fr_words = {w.fr: w for w in words}
se_words = {w.se: w for w in words}
再次,这里更推荐BST。
答案 3 :(得分:0)
为了加速单词查找并获得良好的灵活性,我选择了一个子词典:每个子词典将一种语言的单词翻译成所有可用的语言,顶级词典将每种语言映射到相应的子词典中
例如,如果multidict
是顶级字典,则multidict['english']['ball']
返回(子)字典:
{'english':'ball', 'francais':'ballon', 'svenska':'ball'}
下面是一个实现这种想法的 Multidictionary 类。 为方便起见,它假设所有翻译都以 CSV 格式存储在文本文件中,该格式在初始化时读取,例如:
english,svenska,francais,italiano
school,skola,ecole,scuola
ball,boll,ballon,palla
可以轻松地将任意数量的语言添加到CSV文件中。
class Multidictionary(object):
def __init__(self, fname=None):
'''Init a multidicionary from a CSV file.
The file describes a word per line, separating all the available
translations with a comma.
First file line must list the corresponding languages.
For example:
english,svenska,francais,italiano
school,skola,ecole,scuola
ball,boll,ballon,palla
'''
self.fname = fname
self.multidictionary = {}
if fname is not None:
import csv
with open(fname) as csvfile:
reader = csv.DictReader(csvfile)
for translations in reader:
for lang, word in translations.iteritems():
self.multidictionary.setdefault(lang, {})[word] = translations
def get_available_languages(self):
'''Return the list of available languages.'''
return sorted(self.multidictionary)
def translate(self, word, language):
'''Return a dictionary containing the translations of a word (in a
specified language) into all the available languages.
'''
if language in self.get_available_languages():
translations = self.multidictionary[language].get(word)
else:
print 'Invalid language %r selected' % language
translations = None
return translations
def get_translations(self, word, language):
'''Generate the string containing the translations of a word in a
language into all the other available languages.
'''
translations = self.translate(word, language)
if translations:
other_langs = (lang for lang in translations if lang != language)
lang_trans = ('%s in %s' % (translations[lang], lang) for lang in other_langs)
s = '%s: %s' % (word, ', '.join(lang_trans))
else:
print '%s word %r not found' % (language, word)
s = None
return s
if __name__ == '__main__':
multidict = Multidictionary('multidictionary.csv')
print 'Available languages:', ', '.join(multidict.get_available_languages())
language = raw_input('Choose the input language: ')
word = raw_input('Type a word: ')
translations = multidict.get_translations(word, language)
if translations:
print translations