所以我使用python dictionary构建了一个词汇表应用程序。但我发现了一个有趣的案例,我不知道如何解决
例如,我有一本字典如下。
glos = {'Hypertext Markup Language': 'the standard markup language for documents.',
'HTML': 'the standard markup language for documents.',
'Semantic Hypertext Markup Language': 'HTML that emphasizes the meaning of the encoded information.'}
正如您所看到的,Hypertext Markup Language
的值与HTML
的值相同,但有什么方法可以添加与Semantic Hypertext Markup Language
的值相同的Semantic HTML
密钥吗?
最终产品是这样的:
glos = {'Hypertext Markup Language': 'the standard markup language for documents.',
'HTML': 'the standard markup language for documents.',
'Semantic Hypertext Markup Language': 'HTML that emphasizes the meaning of the encoded information.'
'Semantic HTML': 'HTML that emphasizes the meaning of the encoded information.'}
我想为密钥创建一个新的dict,它的缩写像这个
same_val = {'Hypertext Markup Language': 'HTML'}
之后,它将循环使用glos
dict中的键,通过使用一些正则表达式或任何东西来查找它是否包含same_val
dict的单词,但我不知道如何在代码中正确键入它。
这听起来像是一个非常脆弱的方法。它不适用于复数等变体。我建议不要夸大主词汇表,而是有一个单独的aliases
字典,在查找术语时同时使用glos
和aliases
。例如:
glos = {'Hypertext Markup Language': 'the standard markup language for documents.',
'Semantic Hypertext Markup Language': 'HTML that emphasizes the meaning of the encoded information.'}
aliases = {'HTML': 'Hypertext Markup Language',
'Semantic HTML': 'Semantic Hypertext Markup Language'}
def lookup(term):
return glos.get(term, glos.get(aliases.get(term)))
您希望将一个新密钥'Semantic HTML'
插入到glos
中,其值与密钥'Semantic Hypertext Markup Language'
的值相同。如果我的理解是正确的,那么应该满足您需求的代码如下。在创建glos
对象后添加此项。
glos['Semantic HTML'] = glos['Semantic Hypertext Markup Language']
这是干什么的?我们从字典中获得对应于关键字'Semantic Hypertext Markup Language'
的值,并将相同的值分配回字典,在关键字'Semantic HTML'
下。