import os
# pip install requests
import requests
if not os.path.exists('data'):
os.makedirs("data")
# f = open('./data/hello.txt', mode='w', encoding='UTF-8')
# f.write(text)
# f.close()
# 自动close
# 文本写入
text = input("输入")
with open('./data/hello.txt', mode='w', encoding='UTF-8') as f:
f.write(text)
# 二进制写入
response = requests.get('https://t7.baidu.com/it/u=508006830,4042443322&fm=193&f=GIF')
data = response.content
print(data)
with open('./data/bumeinv.jpg', mode='wb') as f:
f.write(data)
# 读取
with open('./data/hello.txt', mode='r', encoding='UTF-8') as f:
du = f.read()
print(du)
词频统计
## 词频统计案例
# 读取
with open('./data/hello.txt', mode='r', encoding='UTF-8') as f:
text = f.read()
print(text)
text = text.replace(",", "")
print(text)
ts = text.split()
print(ts)
# {"When: 10, }
counts = {}
for word in ts:
counts[word] = counts.get(word, 0) + 1
print(counts)
匿名函数和高阶函数
# 匿名函数 :
# lambda 参数1, 参数2..... : 表达式
s = lambda x, y : x + y
print(s(100, 200))
# 高阶函数: 函数的参数中有函数作为参数
# def add(x, y):
# return x + y
# def sub(x, y):
# return x - y
# def mul(x, y):
# return x * y
# def div(x, y):
# return x / y
# print(add(10, 20))
# siZe就是高阶函数
def siZe(x, y, func):
return func(x, y)
# print(siZe(100, 20, mul))
print(siZe(9, 5, func=lambda a, b: a*b))
print(siZe(9, 5, func=lambda a, b: a+b))
系统高阶函数
# 系统高阶函数 # map 函数接收两个参数, 第一个是一个function, 第二个是一个序列 # map是讲function 依次作用于序列中的每个元素 # ls = [i for i in range(10)] # print(ls) # def processing(x): # return x**2 # print(list(map(processing, ls))) # print(list(map(lambda x:x**2, ls))) print(list(map(lambda x: x**2, [i for i in range(10)]))) print(list(map(str, [i for i in range(10)]))) print(list(map(abs, [i for i in range(-10, 5)]))) # reduce from functools import reduce print(reduce(lambda x, y: x + y, [i for i in range(101)])) print(reduce(lambda x, y: x * y, [i for i in range(10)])) print(reduce(lambda x, y: x * y, [i for i in range(1, 6)])) # filter from random import randint scores = [randint(10, 100) for _ in range(10)] print(scores) print(list(filter(lambda x: x>=60, scores))) print(list(filter(lambda x: x%2==0, scores)))
排序函数
from random import randint, choice
import string
print(string.ascii_letters)
scores = [randint(10, 100) for _ in range(10)]
print(scores)
print(sorted(scores))
print(sorted(scores, reverse=True))
print(scores)
# sorted返回新的排序结果, 不会影响原来的
p_list = []
res = string.ascii_letters
for _ in range(5):
info = {"name":choice(res), "score":randint(10, 100), "sal":randint(3000, 10000)}
p_list.append(info)
for x in p_list:
print(x)
res = sorted(p_list, key=lambda x:x['sal'], reverse=True)
print("#"*100)
for x in res:
print(x)



