Python 三向语言词典
我想创建一个字典(以txt文件的形式存储在本地),用户可以在输入英语、瑞典语或法语单词之间进行选择,以获得该单词在其他两种语言中的翻译。用户还应该能够将数据添加到字典中 当我用英语单词查找瑞典语和法语单词时,代码就起作用了。但是如果我只有value1,我怎么才能得到密钥和Value2呢?Python 三向语言词典,python,dictionary,Python,Dictionary,我想创建一个字典(以txt文件的形式存储在本地),用户可以在输入英语、瑞典语或法语单词之间进行选择,以获得该单词在其他两种语言中的翻译。用户还应该能够将数据添加到字典中 当我用英语单词查找瑞典语和法语单词时,代码就起作用了。但是如果我只有value1,我怎么才能得到密钥和Value2呢? 有没有办法或者我应该尝试以不同的方式来处理这个问题 一个好的选择是,如果未设置值,则为该值存储None。虽然它会增加所需的内存量,但您可以进一步添加语言本身 例如: se_eng_fr_dict = {'Sch
有没有办法或者我应该尝试以不同的方式来处理这个问题 一个好的选择是,如果未设置值,则为该值存储
None
。虽然它会增加所需的内存量,但您可以进一步添加语言本身
例如:
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
也许一组嵌套列表更适合:
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')
然后,您可以通过执行以下操作来访问翻译集:
>>> 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']
同样,这里更推荐BST。为了加快单词查找并实现良好的灵活性,我会选择一个子词典:每个子词典将一种语言的单词翻译成所有可用的语言,顶级词典将每种语言映射到相应的子词典 例如,如果
multidict
是顶级词典,则multidict['english']['ball']
返回(子)词典:
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}
下面是一个实现这种想法的类多字典。
为方便起见,它假设所有翻译都以CSV格式存储到文本文件中,并在初始化时读取,例如:
{'english':'ball', 'francais':'ballon', 'svenska':'ball'}
可以轻松地将任意数量的语言添加到CSV文件中
english,svenska,francais,italiano
school,skola,ecole,scuola
ball,boll,ballon,palla
value1和value2是什么意思?value1=字典中的第一个值(在本例中为Skola或Boll),value2=字典中的第二个值(Ecole、Ballon),您可以简单地循环您的字典项:
>>se_eng_fr_dict={'School':['Skola','Ecole','Ball'],'Ball':['Boll','Ballon]}>>val='Skola'>>,对于我,j在seu eng_fr_dict.items()中:。。。如果j[0]==val:。。。打印i。。。打印j。。。学校['Skola','Ecole']
谢谢!是的,我想这会让事情变得容易一点。不过,我真的很想把这本字典编出来!是的,字典可以工作,但是嵌套的列表是有序的,并且您不必担心从值中提取键(字典对于键到值,而不是值到键很有用)。嵌套列表解决了这个问题。
english,svenska,francais,italiano
school,skola,ecole,scuola
ball,boll,ballon,palla
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