5.24
组合数据类型
字典类型及操作
- 字典类型定义
映射:映射是一种键(索引)和值(数据)
的对应
["python", 123, ",io"]
0 1 2
# 这是序列的默认索引,映射类型则由用户将数据定义为索引
- 字典类型是"映射"的体现
键值对:键是数据索引的扩展
字典是键值对的集合,键值对之间无序
采用大括号{}和dict()创建,键值对用冒号表示
{<键1>:<值1>, <键2>:<值2>, ... ,<键n>:<值n>}
- 字典类型的用法
<字典变量> = {<键1>:<值1>,...,<键n>:<值n>}
<值> = <字典变量>[<键>]
<字典变量>[<键>] = <值>
#[]用来向字典变量中索引或增加元素
字典处理函数及方法
字典应用场景
- 映射的表达
- 字典遍历
for k in d :
jieba库
是一种中文分词第三方库(需要额外安装)
中文本文需要动通过分词获得单个的词语
jieba库提供三种分词模式。
(pip install jieba)
- jieba分词的原理
依靠中文词库,利用一个中文词库,确定汉字之间的关联概率,汉字间概率大的组成词组,形成分词结果,除了分词,用户还可以添加自定义的词组。 - 使用说明
精确模式、全模式、搜索引擎模式
精确模式:把本文精确的切分开,不存在冗余单词
全模式:把本文中所有可能的词语都扫描出来,存在冗余
搜索引擎模式:在精确模式的基础上,对长词再次切分
文本词频统计
- HAMLET
def getText():
txt = open("hamlet.txt", "r").read()
txt = txt.lower() #大写转换为小写
for ch in '|"!@#$%^&*()":?><,./.;'[]]\{}{~`':
txt = txt.replace(ch, "")
return txt
hamletTxt = getText()
words = hamletTxt.split()
counts = {}
for word in words:
counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=Trie)
for i in range(10):
word, count = itmes[i]
print("{0:<10}{1:>5}".format(word, count))
- 三国演义
import jieba
txt = open("....text","r", encoding="utf-8").read()
words = jeiba.lcut(txt)
counts = {}
for word in words:
if len(worf) == 1:
continue
else:
counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(15):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))