博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【语言处理与Python】5.3使用Python字典映射词及其属性
阅读量:4329 次
发布时间:2019-06-06

本文共 1851 字,大约阅读时间需要 6 分钟。

字典数据类型(其他编程语言可能称为关联数组或者哈希数组)

索引链表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']

常用的方法与字典相关习惯用法的总结

转载于:https://www.cnblogs.com/createMoMo/archive/2013/05/25/3099458.html

你可能感兴趣的文章
android学习笔记45——android的数据存储和IO
查看>>
mysql 安装完以后没有mysql服务
查看>>
REP report开发技巧
查看>>
js-ES6学习笔记-编程风格(2)
查看>>
从相册中取图片
查看>>
hdu1874畅通工程再续
查看>>
无线网络不受到攻击与窃听的几个小诀窍
查看>>
JDK中的Timer和TimerTask详解
查看>>
OC2-xml文件解析
查看>>
改变Eclipse 中代码字体大小
查看>>
第五章例题
查看>>
小议 HashMap
查看>>
Docker配置镜像源(windows)
查看>>
MyEclipse安装JS代码提示(Spket插件)
查看>>
QT_8_Qt中的事件处理_定时器事件_定时器类_事件分发器_事件过滤器_绘图事件_高级绘图事件_绘图设备_QFile 文件读写_QFileInfo文件信息...
查看>>
laravel 视图流程控制,if switch for loop
查看>>
Java自学资料——线程
查看>>
Microsoft Visual C++ Runtime Library Runtime Error解决的方式
查看>>
四、Linux/UNIX操作命令积累【chmod、chown、tail】
查看>>
盘点几种喜好“嘲讽”老罗的人
查看>>