复杂排序
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}')