【语言处理与Python】5.3使用Python字典映射词及其属性
2013-05-25 23:18
686 查看
字典数据类型(其他编程语言可能称为关联数组或者哈希数组)
索引链表VS字典(略)
Python字典
#初始化一个空字典
pos={}
#字典的一些其他用法pos.keys0,pos.values(),pos.items()
#定义一个非空字典
通常会使用第一个方法。需要注意的是,一个字典的键是不能修改的。
默认字典
我们可以使用默认字典,这样当访问一个不存在的键时,会赋予默认值,而不是返回错误信息。
设置默认数据类型:
设置默认值:
递增的更新词典
#递增更新字典,按值排序
#一般的积累任务的实现和nltk.Index()提供的更简单的方法对比
颠倒词典
常用的方法与字典相关习惯用法的总结
索引链表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']
常用的方法与字典相关习惯用法的总结
相关文章推荐
- Python自然语言处理学习笔记(42):5.3 使用Python字典将单词映射到属性
- OpenCV3计算机视觉Python语言实现(三):使用OpenCV3处理图像
- 使用Python语言高效地处理一个文本文件
- 【语言处理与Python】11.4使用XML\11.5使用Toolbox数据
- 使用 ElementTree,以 Python 语言处理 XML
- 【语言处理与Python】5.1使用词性标注器/5.2标注语料库
- Python 语言及其应用 Chapter_3_Note_2 容器_列表_元组_字典_集合
- 【语言处理与Python】3.3使用Unicode进行文字处理
- 详解Python中映射类型(字典)操作符的概念和使用
- python使用元组、字典向函数传递多个参数、python冗余参数处理
- 详解Python中映射类型(字典)操作符的概念和使用
- 【语言处理与Python】3.4使用正则表达式检测词组搭配
- Python使用struct处理二进制(pack和unpack用法)
- Python 语言及其应用 Chapter_4_Note_3 闭包_匿名函数lambda_生成器
- VC++中使用内存映射文件处理大文件
- Python 语言及其应用 Chapter_4_Note_6 异常处理
- python语言使用技巧分享
- [Python]面向对象--属性和方法命名使用
- 用python2.7 做sogou字典处理编码的时候踩过的坑——学习笔记【文字编码转换 decode chardet】
- Python字典处理技巧