xieqingrui-python-day07

复杂排序

stu_list = [
    {"name":'张三', 'age': 18, "score":98}, 
    {"name":'李四', 'age': 22, "score":44},
    {"name":'王五', 'age': 33, "score":55},
    {"name":'赵六', 'age': 1, "score":33},
]

print(sorted(stu_list, key=lambda item: item['score']))

文件的写

## 文件的写入
# 文本写入
text = '今天天气不错啊'
# mode='w',写文件  encoding='utf-8' 万国码
file = open('./data/日记.txt', mode='w', encoding='utf-8')
# file.write(text)
file.write(text)

# 二进制写入
# pip install 库名
# pip install requests
import requests
url = "https://img0.baidu.com/it/u=3446889801,995439445&fm=26&fmt=auto&gp=0.jpg"
response = requests.get(url)
data = response.content
print(data)
# mode='wb' 写二进制
f = open('./data/caixunkun.jpg', mode='wb')
f.write(data)


文件的读

## 读取文件
with open('./data/threekingdom.txt', mode='r', encoding='utf-8') as f:
    data = f.read()
    print(data)

综合案例:三国人物TOP10分析

import jieba
with open('./data/threekingdom.txt', mode='r', encoding='utf-8') as f:
    data = f.read()
    data_list = jieba.lcut(data)
    print(data_list)
    counts = {}
    for word in data_list:
        if len(word)<=1:
            continue
        counts[word] = counts.get(word, 0) + 1
    print(counts)
    # 删除
    stop_words = {"将军", "却说", "丞相", "二人", "不可", "荆州", "不能", "如此", "商议",
                      "如何", "主公", "军士", "军马", "左右", "次日", "引兵", "大喜", "天下",
                      "东吴", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人马", "不知",
                  "孔明曰", "玄德曰", "刘备", "云长"}

    counts["孔明"] = counts["孔明"] + counts["孔明曰"]
    counts["关公"] = counts["关公"] + counts["云长"]
    counts["玄德"] = counts["玄德"] + counts["玄德曰"] + counts["刘备"]
    for word in stop_words:
        del counts[word]

    word_list = list(counts.items())
    word_list = sorted(word_list, key=lambda x: x[1], reverse=True)
    for index in range(10):
        name, num = word_list[index]
        print(f'人物名: {name}, 出现频次: {num}')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值