python 学习

numpy相关

# 通道合并
import numpy as np
import cv2

'''
这里需要改一下默认通道顺序,cv2默认的是bgr顺序
'''
img = cv2.imread('./xx.jpeg')[:, :, [2, 1, 0]]
'''
归一化 到 0 ~ 1
'''
img = img/255

Red = img[:, :, 0] * 0.3
Green = img[:, :, 1] * 0.6
Blue = img[:, :, 2] * 0.1

new_img = np.stack((Red, Green, Blue), axis=2)
————————————————
版权声明:本文为CSDN博主「考拉不是大叔」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/kevin198528/article/details/107354815

基本类型

字典

score = {} # 新建一个空字典
score = { key1 : value2, key2 : value2}

# 访问元素
print(score[key1]) # 若键不存在,则报错
print(score.get(key1)) # 若键不存在,则返回None
for name in score:
	print(score[name])

# 删除元素
del score[key1] # 键必须存在

函数

# 默认参数,
def hello(name = 'world')
	print('hello ' + name)

hello()
hello('python')

def func(a, b=5) # 默认参数必须在末尾

模块

import random # 导入整个模块
random.randint(1,10) # 生成[1,10]的随机数
random.choice([3,6,8]) # 从list中随机选择一个元素

dir(random) # 查询模块的所有函数和变量

from math import pi # 导入模块的某个函数或变量
print(pi)

from math import pi as math_pi # 为导入的函数或变量取别名
print(math_pi)

文件操作

重要函数:

f = open('scores.txt') # 默认只读方式打开
data = f.read() # 读取全部内容到字符串中
data = f.readline() # 读取一行内容到字符串中
data = f.readlines() # 按行读取到list中,list的每个元素是一行内容
f.close()

output = open('result.txt','w') # 以写的方式打开,覆盖写入
output = open('result.txt','a') # 追加写入
output.write(line) # 写入字符串
output.writelines(lines) # 写入list

# 字符串操作
data = line.split() # 按空格分割字符串,存储到list中
data = line.split(';') # 按;分割字符串
result = '%s \t: %d'%(data[0],sum) # 格式化写入
results.append(result) # 将元素添加到list末尾


样例:

# -*- coding:utf-8 -*-
f = open('scores.txt', encoding='utf-8') # 读取以utf-8编码的文件
lines = f.readlines() # 按行读取到list中,list的每个元素是一行内容
f.close()
results = []

for line in lines:
	data = line.split()
	sum = 0
	for score in data[1:]:
		sum += int(score)
	result = '%s \t: %d\n'%(data[0],sum)
	results.append(result)

output = open('result.txt','w')
output.writelines(results)
output.close()

异常处理

try:
	f = open('no.txt')
	print('File opened!')
	f.close()
except:
	print('File not exists.')
print('Done.')

综合实例

猜猜猜1

输入名字,从文件中读取记录,最后存储。
重要函数:

name = input('请输入你的名字:')
f = open('game.txt')
lines = f.readlines()
f.close()
scores = {} # 将文件读取存入字典里,字典的键为名字,值为分数
for line in lines:
	s = line.split()
	scores[s[0]] = s[1:]
score = scores.get(name) # 键不存在,则返回None
if score is None:
	score = [0,0,0]

# 最后更改scores[name]的值,再把scores存入文件
scores[name] = [str(game_times),str(min_times),str(total_times)]
result = ''
for n in scores:
	line = n + ' ' + ' '.join(scores[n]) + '\n'
	result += line
f = open('game.txt','w')
f.write(result)
f.close()

参考:
Python 第41课】 用文件保存游戏(3)

下载网页

# python3代码
from urllib import request
web = request.urlopen('http://www.baidu.com')
content = web.read() # 读取的是字节

output = open('baidu.html','w',encoding='utf-8')
output.writelines(content.decode('utf-8'))
output.close()

将二进制文件转换为utf-8编码(可以显示中文)

f = open('city.py') # 二进制文件
data = f.readlines()
f.close()
output = open('city1.py','w',encoding='utf-8')
output.writelines(data)
output.close()

查询天气

# -*- coding:utf-8 -*-
from urllib import request
import json
from city1 import city # 前一个city是模块名,后一个city是变量名

cityname = input('你想查哪个城市的天气?\n')
citycode = city.get(cityname)
if citycode:
	try:
		url = 'http://www.weather.com.cn/data/cityinfo/%s.html'%citycode
		content = request.urlopen(url).read()
		#print(content.decode('utf-8'))
		data = json.loads(content) # 将json字符串转换为dict
		result = data['weatherinfo']
		str_tmp = ('%s\n%s ~ %s')%(result['weather'],result['temp1'],result['temp2'])
		print(str_tmp)
	except:
		print('查询失败')
else:
	print('没有找到该城市')

参考:
【Python 第45课】 查天气(3)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值