(笔记)第6周 组合数据类型

356 阅读2分钟

中国大学MOOC - Python语言程序设计 - 第6周

6.1 集合类型及操作

集合 set

例如:

A = { "python", 123, ("python", 123) }

注意: 空集合不能用 {} 生成,要用 set()。 因为 {} 生成的是空字典 dict

>>> de = {} ; type(de)
<class 'dict'>
>>> se = set() ; type(se)
<class 'set'>

6.2 序列类型及操作

6.3 实例9: 基本统计值计算

6.3

6.4 字典类型及操作

  • 注意:
    • 创建时 dict{} 只能用来创建空字典,不能有参数。
    • 还是得用 a = {1: 1, 2: 2} 这种。

6.4

6.5 模块5: jieba库的使用

6.6 实例10: 文本词频统计

a) 英文 哈姆雷特

#CalHamlet.py

def getText():
    # 读取txt 【√】
    txt = open("hamlet.txt", "rt").read()
    # 归一化处理 【√】
    txt = txt.lower()                               # 全部转化为小写
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':   # 替换掉所有特殊字符
        txt = txt.replace(ch, " ")
    return txt

HamletTxt = getText()           # 读取txt

words = HamletTxt.split()       # 默认以空格分隔,得到所有单词 【√】
counts = dict()                 # 利用字典统计词频 【√】
for word in words:              
    counts[word] = counts.get(word, 0) + 1

items = list(counts.items())    # 转化为list方便处理和排序 【√】
items.sort(key = lambda x:x[1], reverse = True) # 按照items的第二个元素排序,逆序 【√】

for i in range(10):             # 打印出词频统计前十位
    word, count = items[i]
    print("{0:<10}{1:>5}".format(word, count))

b) 中文 三国演义 人名

#CalThreeKingdoms.py
import jieba
           
# 读取txt 【√】                                       # 要补充编码【√】
threeKingdomsTxt = open("threekingdoms.txt", "rt", encoding="utf-8").read()

# 利用jieba库 分词 【√】
words = jieba.lcut(threeKingdomsTxt)   

# 利用字典统计词频
counts = dict()                 
for word in words:
    if len(word) == 1:  # 剔除单字,显然不是人名(也顺带剔除了标点符号)【√】
        continue
    elif word == '玄德' or word == '玄德曰': # 处理别名【√】
        rword = '刘备'
    elif word == '关公' or word == '云长':
        rword = '关羽'
    elif word == '孔明曰' or word == '诸葛亮':
        rword = '孔明'
    elif word == '丞相' or word == "孟德":
        rword = '曹操'
    else:
        rword = word
    counts[rword] = counts.get(rword, 0) + 1

# 剔除非人名 【√】
for i in ['却说', '将军', '二人', '不可', '荆州', '不能', '如此', '主公', \
            '军士', '商议', '如何', '引兵', '次日', '左右', '军马', '大喜', \
            '天下', '东吴', '于是', '今日', '不敢', '魏兵', '陛下', '一人', \
            '都督', '人马', '不知', '汉中', '只见']:
    del counts[i]

items = list(counts.items())    # 转化为list方便处理和排序
items.sort(key = lambda x:x[1], reverse = True) # 按照items的第二个元素排序,逆序

for i in range(10):             # 打印出词频统计前10位
    word, count = items[i]
    print("{0:<10}{1:>5}".format(word, count))

results

曹操         1451
孔明         1383
刘备         1252
关羽          784
张飞          358
吕布          300
赵云          278
孙权          264
司马懿         221
周瑜          217

练习题

测验6: 组合数据类型 (第6周)-单选题

有一些概念不太熟,所以这些题需要多注意。