写文件
text = 'hello hi 你好\n哈哈'
f = open('./data/hello.txt', mode='a', encoding='UTF-8')
f.write(text)
f.close()
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()
读文件
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)
ls.sort(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=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)