字典数据类型(其他编程语言可能称为关联数组或者哈希数组)
索引链表VS字典(略)
Python字典
#初始化一个空字典
pos={}
#字典的一些其他用法pos.keys0,pos.values(),pos.items()
#定义一个非空字典
>>>pos= { 'colorless':'ADJ', 'ideas': 'N', 'sleep': 'V', 'furiously': 'ADV'}>>>pos= dict(colorless='ADJ',ideas='N', sleep='V', furiously='ADV')
通常会使用第一个方法。需要注意的是,一个字典的键是不能修改的。
默认字典
我们可以使用默认字典,这样当访问一个不存在的键时,会赋予默认值,而不是返回错误信息。
设置默认数据类型:
>>>frequency = nltk.defaultdict(int)>>>frequency['colorless'] = 4>>>frequency['ideas']0>>>pos= nltk.defaultdict(list)>>>pos['sleep']= ['N', 'V']>>>pos['ideas'][]
设置默认值:
>>>pos= nltk.defaultdict(lambda: 'N')>>>pos['colorless']= 'ADJ'>>>pos['blog']�'N'>>>pos.items()
[('blog', 'N'), ('colorless', 'ADJ')]
递增的更新词典
#递增更新字典,按值排序
>>>counts = nltk.defaultdict(int)>>>from nltk.corpusimport brown>>>for (word, tag) in brown.tagged_words(categories='news'):... counts[tag]+=1...>>>counts['N']22226>>>list(counts)['FW', 'DET', 'WH', "''", 'VBZ', 'VB+PPO', "'", ')', 'ADJ', 'PRO', '*', '-', ...]>>>from operator import itemgetter>>>sorted(counts.items(), key=itemgetter(1),reverse=True)[('N', 22226),('P', 10845),('DET', 10648),('NP', 8336),('V', 7313), ...]>>>[t for t, c in sorted(counts.items(), key=itemgetter(1),reverse=True)]['N', 'P', 'DET', 'NP', 'V', 'ADJ', ',', '.', 'CNJ', 'PRO', 'ADV', 'VD', ...]
#一般的积累任务的实现和nltk.Index()提供的更简单的方法对比
>>>anagrams = nltk.defaultdict(list)>>>for wordin words:... key= ''.join(sorted(word))... anagrams[key].append(word)...>>>anagrams['aeilnrt']['entrail', 'latrine', 'ratline', 'reliant', 'retinal', 'trenail']
>>>anagrams = nltk.Index((''.join(sorted(w)),w)for win words)>>>anagrams['aeilnrt']['entrail', 'latrine', 'ratline', 'reliant', 'retinal', 'trenail']
颠倒词典
>>>pos2= nltk.Index((value, key) for (key, value) in pos.items())>>>pos2['ADV']['peacefully', 'furiously']
常用的方法与字典相关习惯用法的总结