基础10·词频统计(词频统计,字典列表转换,文本读取,lambda定义方法,桌面文件打开方法,字典格式生成,字典的键与指定值的写入)

参考点
词频统计,字典列表转换,文本读取,lambda定义方法,桌面文件打开方法,字典格式生成,字典格式生成,字典的键与指定值的写入

def getText():
    txt = open("C://Users/Administrator/Desktop/"+"三国演义(前四回).txt", "r",).read()
    txt = txt.lower()                               # lower() 方法转换字符串中所有大写字符为小写。
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")                   # 将文本中特殊字符替换为空格
    return txt
hamletTxt = getText()
words = hamletTxt.split()                            #以空格为分割,将字符串转换为列表
counts = {}                                          #建立空字典
for word in words:                                   #get() 函数返回指定键的值,如果值不在字典中返回默认值。
    counts[word] = counts.get(word,0)+1              #字典格式生成,字典的键与指定值的写入
items = list(counts.items())                         #字典列表转换:[(key:data),(key1:data1)]
items.sort(key=lambda x: x[1], reverse=True)         #sort() 函数用于排序,lambda一种函数定义,类似def
for i in range(10):                                  #取前十
    word, count = items[i]                           #item[]:索引
    print("{0:<10}\t{1:>5}".format(word, count))     #键值对赋值给word,count;制表符应用

结果展示

肃曰:       	    9
进曰:       	    8
布曰:       	    8
玄德曰:      	    6
飞曰:       	    4
帝曰:       	    4
天公将军      	    3
地公将军      	    3
袁绍曰:      	    3
且容商议。     	    3

补充
字典的键与指定值的写入

c={"1":"a","2":"b"}
i="3"
c[i]="c"
print(c)

结果:

{'1': 'a', '2': 'b', '3': 'c'}

在这里插入图片描述
(注:图片来自mooc蒿天老师课程)

猜你喜欢

转载自blog.csdn.net/qq_44534317/article/details/89294984
今日推荐