huyuhang-day09

写文件


#
text = 'hello hi 你好\n哈哈'
# , mode='w' 写文件
f = open('./data/hello.txt', mode='a', encoding='UTF-8')
f.write(text)
f.close()
# 写入二进制
# pip install 模块名
# pip install requests
import requests
url = 'https://img2.baidu.com/it/u=2860640912,1833965317&fm=26&fmt=auto&gp=0.jpg'
response = requests.get(url)
img_data = response.content
print(img_data)
# 写二进制
f = open('./data/cat.jpg', mode='wb')
f.write(img_data)
f.close()

读文件

# f = open('./data/threekingdom.txt', mode='r', encoding='utf-8')
# data = f.read()
# f.close()


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

排序

#
from random import randint
ls = [randint(1, 100) for _ in range(10)]
print(ls)
# 1. 排序
ls.sort(reverse=True) # reverse=True降序排序
print("排序后", ls)
ls = [randint(1, 100) for _  in range(10)]
print(ls)
ls = sorted(ls, reverse=True)
print(ls)

# 复杂类型的排序
infos = [
    {"name": "张三", "age": 19, "score": 99},
    {"name": "李四", "age": 12, "score": 80},
    {"name": "王五", "age": 20, "score": 39},
    {"name": "赵六", "age": 30, "score": 70},
]

# 按照成绩进行排序
def sort_by_score(d):
    return d['age']
# 按照什么进行排序
# infos.sort(key=sort_by_score, reverse=True)
infos.sort(key=lambda d: d['age'], reverse=True)
print(infos)

score_d = {"张三": 111, "李四": 50, "王五": 60, "赵六": 90}
# 转化成列表进行排序
res_ls = list(score_d.items())
print(res_ls)
res_ls = sorted(res_ls, key=lambda t:t[1])
print(res_ls)


探究三国人物出场频次TOP10

import jieba
with open('./data/threekingdom.txt', mode='r', encoding='utf-8') as f:
    data = f.read()
    print(len(data))
    word_list = jieba.lcut(data)
    print(word_list)
    print(len(word_list))
    counts = {}
    for word in word_list:
        if len(word) <= 1:
            continue
        counts[word] = counts.get(word, 0) + 1
    print(counts)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值