文件的使用方式:打开-操作-关闭
文件路径:
绝对路径和相对路径
文本文件&二进制文件,open( , )和.close()
文件内容的读取:.read() .readline() .readlines()
数据的文件写入:.write() .writelines() .seek()
文件的逐行操作
#一次读入,分行处理
frame=input("请输入想要打开的文件名称:")
f=open(frame,"r")
for line in f.readlines():
print(line)
f.close()
#分行读入,逐行处理(更好)
frame=input("请输入想要打开的文件名称:")
f=open(frame,"r")
for line in f:
print(line)
f.close()
#将一个元素全为字符串的列表写入文件
#没有换行
<f>.writelines(lines)
理解方法思维
自动化思维:数据和功能分离,数据驱动的自动运行
接口化设计:格式化设计接口,清晰明了
二维数据应用:应用维度组织数据,二维数据最常用
应用问题的扩展
扩展接口设计,增加更多控制接口
扩展功能设计,增加弧形等更多功能
扩展应用需求,发展自动轨迹绘制到动画绘制
# coding:utf-8
import turtle
turtle.title("自动轨迹绘制")
turtle.setup(800, 600,0,0)
turtle.pencolor("red")
turtle.pensize(5)
datals=[]
f=open("data.txt",encoding="UTF-8")
for line in f:
line=line.replace("\n","")
datals.append(list(map(eval,line.split(","))))
f.close()
for i in range(len(datals)):
turtle.pencolor(datals[i][3],datals[i][4],datals[i][5])
turtle.fd(datals[i][0])
if datals[i][1]:
turtle.right(datals[i][2])
else:
turtle.left(datals[i][2])
数据的维度:一维、二维、多维、高维
一维数据的表示:列表类型(有序)和集合类型(无序)
一维数据的存储:空格分隔、逗号分隔、特殊符号分隔
一维数据的处理:字符串方法 .split() 和 .join()
二维数据的表示:列表类型,其中每个元素也是一个列表
CSV格式:逗号分隔表示一维,按行分隔表示二维
二维数据的处理:for循环+.split()和.join()
#二维数据处理
fo=open(frame)
ls=[]
for line in fo:
ls.append(list(line.replace("\n","").split(",")))
#数据写入CSV格式的文件
ls=[[],[],[]]
f=open(frame,"w")
for item in ls:
f.write(",".join(item)+"\n")
f.close()
#采用二层循环逐一处理
ls=[[1,2],[3,4],[5,6]]
for row in ls:
for column in row:
print(column)
wordcloud 库常规方法
步骤1:配置对象参数
步骤2:加载词云文本
步骤3:输出词云文件
import wordcloud
c = wordcloud.WordCloud()
c.generate(“wordcloud by Python”)
c.to_file(“pywordcloud.png”)
#中文词云需要分词
import wordcloud
import jieba
txt = "程序设计语言是计算机能够理解和识别用户操作意图的一种交互体系,它按照特定规则组织计算机指令,使计算机能够自动进行各种运算处理。"
w = wordcloud.WordCloud(width=500,font_path="msyh.ttc",height=400,background_color='white')
w.generate(" ".join(jieba.lcut(txt)))
w.to_file("pywcloud.png")
#GovRptWordCloudv2.py
import jieba
import wordcloud
from imageio import imread
mask = imread("fivestar.png")
f = open("新时代中国特色社会主义.txt", "r", encoding="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud( font_path = "msyh.ttc", mask = mask,
width = 1000, height = 700, background_color = "white")
w.generate(txt)
w.to_file("grwordcloud.png")
打印输出附件文件的有效行数,注意:空行不计算为有效行数。
附件为:latex.log
for line in f方式获得的每行内容(在变量line中)包含换行符,所以,要通过strip()函数去掉换行符后再进行统计。这里,空行指没有字符的行。
f = open("latex.log")
s = 0
for line in f:
line = line.strip('\n')
if len(line) == 0:
continue
s += 1
print("共{}行".format(s))
使用 ord(‘a’)+i 配合 range()函数 可以遍历一个连续的字符表。
f = open("latex.log")
cc = 0
d = {
}
for i in range(26):
d[chr(ord('a')+i)] = 0
for line in f:
for c in line:
d[c] = d.get(c, 0) + 1
cc += 1
print("共{}字符".format(cc), end="")
for i in range(26):
if d[chr(ord('a')+i)] != 0:
print(",{}:{}".format(chr(ord('a')+i), d[chr(ord('a')+i)]), end="")
统计附件文件中与其他任何其他行都不同的行的数量,即独特行的数量。
需要"去重"功能,请使用集合类型。
ls.remove()可以去掉某一个元素,如果该行是独特行,去掉该元素后将不在集合t中出现。
找到不同行数,那就要用每一行分别和出它以外剩余所有行比较,然后如果剩余所有行中有和它相同的行,那么它就不是独特行,需要跳过。
f = open("latex.log")
ls = f.readlines()
s = set(ls)
for i in s:
ls.remove(i)
t = set(ls)
print("共{}独特行".format(len(s)-len(t)))
附件是一个CSV文件,请将每行按照列逆序排列后输出,不改变各元素格式(如周围空格布局等)。
f = open("data.csv")
for line in f:
line = line.strip("\n")
ls = line.split(",")
ls = ls[::-1]
print(",".join(ls))
f.close()
该CSV文件的每个数据中不包含空格,因此,可以通过替换空格方式来清洗。如果数据中包含空格,该方法则不适用。
f = open("data.csv")
s = f.read()
s = s.replace(" ","")
print(s)
f.close()
for line in f获取的line包含每行最后的换行符(\n),所以,去掉该换行符进行统计。
f=open("latex.log")
s=0
count=0
for line in f:
line=line.strip("\n")
if line=="":
continue
s+=len(line)
count+=1
print(round(s/count))
使用strip()方法去掉每行最后的回车,使用replace()去掉每行元素两侧的空格。
f=open("data.csv")
ls=f.readlines()
ls=ls[::-1]
lt=[]
for line in ls:
line=line.strip("\n")
line=line.replace(" ","")
lt=line.split(",")
lt=lt[::-1]
print(";".join(lt))
f.close()
自顶向下
解决复杂问题的有效方法
自底向上
逐步组建复杂系统的有效测试方法
代码:
# coding:utf-8
from random import random
def printIntro():
print("这个程序模拟两个选手A和B的某种竞技比赛")
print("程序运行需要A和B的能力值(以0到1之间的小数表示)")
def getInputs():
a=eval(input("请输入选手A的能力值(0-1):"))
b= eval(input("请输入选手B的能力值(0-1):"))
n= eval(input("模拟比赛的场次:"))
return a,b,n
def simNGames(n,probA,probB):
winsA,winsB=0,0
for i in range(n):
scoreA,scoreB=simOneGame(probA,probB)
if scoreA > scoreB:
winsA+=1
else:
winsB+=1
return winsA,winsB
#比赛结束
def gameOver(a,b):
return a==15 or b==15
#模拟一局比赛
def simOneGame(probA,probB):
scoreA,scoreB=0,0
#发球
serving="A"
while not gameOver(scoreA,scoreB):
if serving=="A":
if random()<probA:
scoreA+=1
else:
serving="B"
else:
if random()<probB:
scoreB+=1
else:
serving="A"
return scoreA,scoreB
#根据A,B获胜场次,打印相关信息
def printSummary(winsA,winsB):
n=winsA+winsB
print("竞技分析开始,共模拟{}场比赛".format(n))
print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA,winsA/n))
print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB, winsB/n))
def main():
#打印介绍信息,获得用户体验
printIntro()
#通过getInputs函数获得球员A,B的能力值以及比赛场次
proA,proB,n=getInputs()
#通过simNGames函数
winA,winB=simNGames(n,proA,proB)
printSummary(winA,winB)
main()
计算思维:抽象计算过程和自动化执行
计算思维与程序设计
计算生态:竞争发展、相互依存、快速更迭
IPO、自顶向下、模块化、配置化、应用开发的四个步骤
PyPI:Python Package Index
pip命令的各种用法
Anaconda集成开发工具及安装方法
UCI页面的“补丁”安装方法
链接:添加链接描述
os.chdir(path) 修改当前程序操作的路径
os.getcwd() 返回程序的当前路径
os.getlogin() 获得当前系统登录用户名称
os.cpu_count() 获得当前系统的CPU数量
os.urandom(n) 获得n个字节长度的随机字符串,通常用于加解密运算
编写各类自动化运行程序的脚本,调用已有程序
扩展应用:安装更多第三方库,增加配置文件
扩展异常检测:捕获更多异常类型,程序更稳定友好
#第三方库自动安装脚本
import os
libs = {
"numpy","matplotlib","pillow","sklearn","requests",\
"jieba","beautifulsoup4","wheel","networkx","sympy",\
"pyinstaller","django","flask","werobot","pyqt5",\
"pandas","pyopengl","pypdf2","docopt","pygame"}
try:
for lib in libs:
os.system("pip install " + lib)
print("Successful")
except:
print("Failed Somehow")
自动化脚本+ - 编写各类自动化运行程序的脚本,调用已有程序
# 1.英文字符的鲁棒输入
alpha = []
for i in range(26):
alpha.append(chr(ord('a') + i))
alpha.append(chr(ord('A') + i))
s = input()
for c in s:
if c in alpha:
print(c, end="")
s=input()
try:
if complex(s)==complex(eval(s)):
print(eval(s)**2)
except:
print("输入有误")
import numpy as np
def npSum():
a = np.array([0, 1, 2, 3, 4])
b = np.array([9, 8, 7, 6, 5])
c = a ** 2 + b ** 3
return c
print(npSum())
Matplotlib: 高质量的二维数据可视化功能库
Seaborn: 统计类数据可视化功能库
Mayavi:三维科学数据可视化功能库
PyPDF2:用来处理pdf文件的工具集
from PyPDF2 import PdfFileReader, PdfFileMerger
merger = PdfFileMerger()
input1 = open("document1.pdf", "rb")
input2 = open("document2.pdf", "rb")
merger.append(fileobj = input1, pages = (0,3))
merger.merge(position = 2, fileobj = input2, pages = (0,1))
output = open("document-output.pdf", "wb")
merger.write(output)
NLTK:自然语言文本处理第三方库
from nltk.corpus import treebank
t = treebank.parsed_sents('wsj_0001.mrg')[0]
t.draw()
Python-docx:创建或更新Microsoft Word文件的第三方库
from docx import Document
document = Document()
document.add_heading('Document Title', 0)
p = document.add_paragraph('A plain paragraph having some ')
document.add_page_break()
document.save('demo.docx')
Scikit-learn:机器学习方法工具集
TensorFlow:AlphaGo背后的机器学习计算框架
import tensorflow as tf
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
res = sess.run(result)
print('result:', res)
MXNet:基于神经网络的深度学习计算框架
通用雷达图绘制:matplotlib库
# -*- coding: utf-8 -*-
#HollandRadarDraw
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family']='SimHei'
radar_labels = np.array(['研究型(I)','艺术型(A)','社会型(S)',
'企业型(E)','常规型(C)','现实型(R)'])
data = np.array([[0.40, 0.32, 0.35, 0.30, 0.30, 0.88],
[0.85, 0.35, 0.30, 0.40, 0.40, 0.30],
[0.43, 0.89, 0.30, 0.28, 0.22, 0.30],
[0.30, 0.25, 0.48, 0.85, 0.45, 0.40],
[0.20, 0.38, 0.87, 0.45, 0.32, 0.28],
[0.34, 0.31, 0.38, 0.40, 0.92, 0.28]]) #数据值
data_labels = ('艺术家','实验员','工程师','推销员','社会工作者','记事员')
angles = np.linspace(0, 2*np.pi, 6, endpoint=False)
data = np.concatenate((data, [data[0]]))
angles = np.concatenate((angles, [angles[0]]))
fig = plt.figure(facecolor="white")
plt.subplot(111, polar=True)
plt.plot(angles,data,'o-', linewidth=1, alpha=0.2)
plt.fill(angles,data, alpha=0.25)
plt.thetagrids(angles*180/np.pi, radar_labels,frac = 1.2)
plt.figtext(0.52, 0.95, '霍兰德人格分析', ha='center', size=20)
legend = plt.legend(data_labels, loc=(0.94, 0.80), labelspacing=0.1)
plt.setp(legend.get_texts(), fontsize='large')
plt.grid(True)
plt.savefig('holland_radar.jpg')
plt.show()
目标 + 沉浸 + 熟练
编程的目标感:寻找感兴趣的目标,寻(wa)觅(jue)之
编程的沉浸感:寻找可实现的方法,思(zuo)考(mo)之
编程的熟练度:练习、练习、再练习,熟练之
Requests: 最友好的网络爬虫功能库
import requests
r = requests.get('https://api.github.com/user',
auth=('user', 'pass'))
r.status_code
r.headers['content-type']
r.encoding
r.text
Scrapy: 优秀的网络爬虫框架
pyspider: 强大的Web页面爬取系统
Beautiful Soup: HTML和XML的解析库
Python-Goose: 提取文章类型Web页面的功能库
from goose import Goose
url = 'http://www.elmundo.es/elmundo/2012/10/28/espana/1351388909.html'
g = Goose({
'use_meta_language': False, 'target_language':'es'})
article = g.extract(url=url)
article.cleaned_text[:150]
Django: 最流行的Web应用框架
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
return Response('Hello World!')
if __name__ == '__main__':
with Configurator() as config:
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()
Flask: Web应用开发微框架
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
WeRoBot: 微信公众号开发框架
import werobot
robot = werobot.WeRoBot(token='tokenhere') @robot.handler
def hello(message):
return 'Hello World!'
aip: 百度AI开放平台接口
MyQR: 二维码生成第三方库
总结:
PyQt5: Qt开发框架的Python接口
wxPython: 跨平台GUI开发框架
import wx
app = wx.App(False)
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show(True)
app.MainLoop()
PyGObject: 使用GTK+开发GUI的功能库
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
window = Gtk.Window(title="Hello World")
window.show()
window.connect("destroy", Gtk.main_quit)
Gtk.main()
PyGame: 简单的游戏开发功能库
Panda3D: 开源、跨平台的3D渲染和游戏开发库
cocos2d: 构建2D游戏和图形界面交互式应用的框架
VR Zero: 在树莓派上开发VR应用的Python库 - 提供大量与VR开发相关的功能
pyovr: Oculus Rift的Python开发接口
Vizard: 基于Python的通用VR开发引擎
turtle 海龟绘图体系
Quads: 迭代的艺术
ascii_art: ASCII艺术库
总结:
PyQt5、wxPython、PyGObject
PyGame、Panda3D、cocos2d
VR Zero、pyovr、Vizard
Quads、ascii_art、turtle
代码展示:
# -*- coding: utf-8 -*-
import turtle as t
# 定义一个曲线绘制函数
def DegreeCurve(n, r, d=1):
for i in range(n):
t.left(d)
t.circle(r, abs(d))
# 初始位置设定
s = 0.2 # size
t.setup(450*5*s, 750*5*s)
t.pencolor("black")
t.fillcolor("red")
t.speed(100)
t.penup()
t.goto(0, 900*s)
t.pendown()
# 绘制花朵形状
t.begin_fill()
t.circle(200*s,30)
DegreeCurve(60, 50*s)
t.circle(200*s,30)
DegreeCurve(4, 100*s)
t.circle(200*s,50)
DegreeCurve(50, 50*s)
t.circle(350*s,65)
DegreeCurve(40, 70*s)
t.circle(150*s,50)
DegreeCurve(20, 50*s, -1)
t.circle(400*s,60)
DegreeCurve(18, 50*s)
t.fd(250*s)
t.right(150)
t.circle(-500*s,12)
t.left(140)
t.circle(550*s,110)
t.left(27)
t.circle(650*s,100)
t.left(130)
t.circle(-300*s,20)
t.right(123)
t.circle(220*s,57)
t.end_fill()
# 绘制花枝形状
t.left(120)
t.fd(280*s)
t.left(115)
t.circle(300*s,33)
t.left(180)
t.circle(-300*s,33)
DegreeCurve(70, 225*s, -1)
t.circle(350*s,104)
t.left(90)
t.circle(200*s,105)
t.circle(-500*s,63)
t.penup()
t.goto(170*s,-30*s)
t.pendown()
t.left(160)
DegreeCurve(20, 2500*s)
DegreeCurve(220, 250*s, -1)
# 绘制一个绿色叶子
t.fillcolor('green')
t.penup()
t.goto(670*s,-180*s)
t.pendown()
t.right(140)
t.begin_fill()
t.circle(300*s,120)
t.left(60)
t.circle(300*s,120)
t.end_fill()
t.penup()
t.goto(180*s,-550*s)
t.pendown()
t.right(85)
t.circle(600*s,40)
# 绘制另一个绿色叶子
t.penup()
t.goto(-150*s,-1000*s)
t.pendown()
t.begin_fill()
t.rt(120)
t.circle(300*s,115)
t.left(75)
t.circle(300*s,100)
t.end_fill()
t.penup()
t.goto(430*s,-1070*s)
t.pendown()
t.right(30)
t.circle(-600*s,35)
t.done()
举一反三
艺术之于编程,设计之于编程
编程不重要,思想才重要!
import sys
print("RECLIMIT:{}, EXEPATH:{}, UNICODE:{}".format(sys.getrecursionlimit(), sys.executable, sys.maxunicode))
from tabulate import tabulate
data = [ ["北京理工大学", "985", 2000], \
["清华大学", "985", 3000], \
["大连理工大学", "985", 4000], \
["深圳大学", "211", 2000], \
["沈阳大学", "省本", 2000], \
]
print(tabulate(data, tablefmt="grid"))
s=input()
lst=[]
for i in s:
if i==" ":
continue
print(i,end="")
#答案更简便
text=input()
print(text.replace("\n",""))
with open("latex.log") as f:
file=f.readlines()
set_file=set(file)
print("共%d关键行"%len(set_file))
try:
s = input()
s=eval(s)
d = {
}
for i in s:
d[s[i]]=i
print(d)
except:
print("输入错误")
import jieba
with open("沉默的羔羊.txt",encoding="utf-8") as f:
file=jieba.lcut(f.read())
d={
}
for line in file:
if len(line)>=2:
d[line]=d.get(line,0)+1
#方法1:
items=list(d.items())
items.sort(key=lambda x:x[1],reverse=True)
print(items[0][0])
#方法2:
maxc=0
maxw=''
for k in d:
if d[k]>maxc:
maxc=d[k]
maxw=k
if d[k] ==maxc and k>maxw:
maxw=k
print(maxw)