首页 > 代码库 > Python基础3(2017-07-20)
Python基础3(2017-07-20)
1、文件操作
现有文件如下:
We were both young when I first saw you
当我第一次看见你的时候,我们都还年轻
I close my eyes and the flashback starts
我闭上眼睛,一幕幕往事又在脑海中重现
I‘m standing there on a balcony in summer air
我站在阳台上,空气里,浓浓的,是夏天的味道
See the lights, see the party, the ball gowns
看见灯火,看见热闹的舞会,华丽的盛装
See you make your way through the crowd
看见你费劲地从人群中挤出来
And say hello, little did I know
That you were Romeo
对我打招呼,呵,至少让我知道了你的名字叫“罗密欧”
You were throwing pebbles
你(对着我家的窗户)扔小石子儿
And my daddy said stay away from Juliet
我爸爸气急败坏地叫你离我远一点
And I was crying on the staircase
(可是这时)我却蜷坐在楼梯间里偷偷地抹眼泪
Begging you please don‘t go
在心底里祈求你不要离开
And I said
我说
Romeo, take me somewhere we can be alone
罗密欧,带我走吧,一起去到一个我们可以相依相偎的地方
I‘ll be waiting, all there‘s left to do is run
我一直在等待(这一天),只有逃离才能让我们摆脱束缚
You‘ll be the prince and I‘ll be the princess
(到那时)我们就可以像王子和公主一样(快乐地在一起)
It‘s a love story, baby, just say yes
这是多么美好的爱情故事呀,亲爱的,答应我吧
So I sneak out to the garden to see you
于是,我偷偷摸摸地溜到小花园去见你
We keep quiet ‘cause we‘re dead if they knew
我们压抑着声息,被他们发现我们就完蛋了
So close your eyes,
Love Story MV
那么,闭上你的双眼
escape this town for a little while
逃避这个喧嚣的尘世,即使只有如此短暂的一刻
Oh, oh, oh
‘Cause you were Romeo,
正因为你的出现
I was a scarlet letter
我的生命才有了如此鲜艳的光彩
And my daddy said stay away from Juliet
我爸爸气急败坏地叫你离我远一点
But you were everything to me
但我又怎么能够承受没有你的痛苦
I was begging you please don‘t go
于是,我无时无刻不在祈求你不要离开
And I said
我说,
Romeo, take me somewhere we can be alone
罗密欧,带我走吧,一起去到一个我们可以相依相偎的地方
I‘ll be waiting, all there‘s left to do is run
我一直在等待(这一天),只有逃离才能让我们摆脱束缚
You‘ll be the prince and I‘ll be the princess
(到那时)我们就可以像王子和公主一样(快乐地在一起)
It‘s a love story, baby, just say yes
这是多么美好的爱情故事呀,亲爱的,答应我吧
Romeo, save me,
罗密欧,拯救我痛苦的灵魂吧
they‘re trying to tell me how to feel
Love Story MV
他们总在试图左右我的思想
This love is difficult, but it‘s real
我们的爱情面对着重重的困难,却无比的忠诚坚贞
Don‘t be afraid, we‘ll make it out of this mess
不要害怕,(我相信)我们终究会冲破困境
It‘s a love story, baby, just say yes
这就是我们的爱情,亲爱的,请答应我
oh,oh
I got tired of waiting,
我厌倦了似乎无穷无尽的等待
wondering if you were ever coming around
渐渐开始怀疑你是否会如期出现在我面前
My faith in you was fading
曾经坚定的信念,也渐渐开始动摇
When I met you on the outskirts of town
当我再一次在小镇的郊外与你相会
And I said
我说,
Romeo save me, I‘ve been feeling so alone
罗密欧,救救我,我再也无法承受这孤独的煎熬
I keep waiting for you but you never come
我一直在等着你,而你却沓然无踪
Is this in my head, I don‘t know what to think
我脑子里乱糟糟的,一片空白,又像是一团浆糊
He knelt to the ground and he pulled out a ring
梦中的他此时正虔诚地跪在我的面前,捧出一枚戒指
And said
他说,
Marry me, Juliet, you‘ll never have to be alone
嫁给我吧,茱丽叶,你再也不会是独自一人
I love you and that‘s all I really know
Love Story MV
我爱你,我只知道这一件事情
I talked to your dad,
我和你的父亲谈过了,
go pick out a white dress
快去挑选你洁白的嫁衣
It‘s a love story, baby, just say yes
这是我们的爱情故事,宝贝请答应我
Oh, oh, oh, oh
噢,我不禁又想起了,
We were both young when I first saw you
我第一次看见你的时候,那时,我们还年轻
基本操作
f = open("song", "r", encoding = "utf-8")
print("This is the fisrt line in text file :\n >>>>", f.readline())#读取单行
data = http://www.mamicode.com/f.read()>
输出结果
This is the fisrt line in text file : >>>> We were both young when I first saw you
#文本内容太长,就不打印了
打开文件的模式有:
1.r,只读模式(默认)
2.w,只写模式(不可读,不存在文件则创建,存在则删除)
3.a,追加模式(可读,不存在则创建,存在则追加)
"+"表示同时可以读写文件
1,"r+",可读可写文件。(可读可写可追加)
2,"w+"写读
3,"a+", 同a
"U"表示在读取时,将\r\n自动转换为\n(与r或者r+模式一同用)
1.rU
2.r+U
"b"表示处理二进制文件(rb,wb,ab)
其他操作语法
def close(self): # real signature unknown; restored from __doc__
"""
Close the file.
A closed file cannot be used for further I/O operations. close() may be
called more than once without error.
"""
pass
def fileno(self, *args, **kwargs): # real signature unknown
""" Return the underlying file descriptor (an integer). """
pass
def isatty(self, *args, **kwargs): # real signature unknown
""" True if the file is connected to a TTY device. """
pass
def read(self, size=-1): # known case of _io.FileIO.read
"""
注意,不一定能全读回来
Read at most size bytes, returned as bytes.
Only makes one system call, so less data may be returned than requested.
In non-blocking mode, returns None if no data is available.
Return an empty bytes object at EOF.
"""
return ""
def readable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a read mode. """
pass
def readall(self, *args, **kwargs): # real signature unknown
"""
Read all data from the file, returned as bytes.
In non-blocking mode, returns as much as is immediately available,
or None if no data is available. Return an empty bytes object at EOF.
"""
pass
def readinto(self): # real signature unknown; restored from __doc__
""" Same as RawIOBase.readinto(). """
pass #不要用,没人知道它是干嘛用的
def seek(self, *args, **kwargs): # real signature unknown
"""
Move to new file position and return the file position.
Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
are SEEK_CUR or 1 (move relative to current position, positive or negative),
and SEEK_END or 2 (move relative to end of file, usually negative, although
many platforms allow seeking beyond the end of a file).
Note that not all file objects are seekable.
"""
pass
def seekable(self, *args, **kwargs): # real signature unknown
""" True if file supports random-access. """
pass
def tell(self, *args, **kwargs): # real signature unknown
"""
Current file position.
Can raise OSError for non seekable files.
"""
pass
def truncate(self, *args, **kwargs): # real signature unknown
"""
Truncate the file to at most size bytes and return the truncated size.
Size defaults to the current file position, as returned by tell().
The current file position is changed to the value of size.
"""
pass
def writable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a write mode. """
pass
def write(self, *args, **kwargs): # real signature unknown
"""
Write bytes b to file, return number written.
Only makes one system call, so not all of the data may be written.
The number of bytes actually written is returned. In non-blocking mode,
returns None if the write would block.
"""
pass
with语句
1,为了避免文件忘记关闭
with open("song", "r", encoding="utf-8") as f:
data = http://www.mamicode.com/f.read()>
如此,with代码执行完毕,会自动关闭文件,释放内存
2,with支持对多个文件的处理
with open("song", "r", encoding="utf-8") as f, open("song1", "r", encoding="utf-8") as f1:
for line in f:
print((line))
2,字符编码与解码
encode & decode
详细文章:
http://www.cnblogs.com/yuanchenqi/articles/5956943.html
http://www.diveintopython3.net/strings.html
需知:
1.在python2默认编码是ASCII, python3里默认是unicode
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
#-*-coding:gb2312 -*- #这个也可以去掉
__author__ = ‘Alex Li‘
import sys
print(sys.getdefaultencoding())
msg = "我爱北京天安门"
#msg_gb2312 = msg.decode("utf-8").encode("gb2312")
msg_gb2312 = msg.encode("gb2312") #默认就是unicode,不用再decode,喜大普奔
gb2312_to_unicode = msg_gb2312.decode("gb2312")
gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8")
print(msg)
print(msg_gb2312)
print(gb2312_to_unicode)
print(gb2312_to_utf8)
in python3
3,函数
引言
我们先用之前的读文件举个例子:
如果我们读完3个文件,每次读完以后在文件最后加一句标记
with open("song", "r+", encoding="utf-8") as f:
for line in f:
print(line)
print("Read file successfully !")
with open("song1", "r+", encoding="utf-8") as f1:
for line1 in f1:
print(line1)
print("Read file successfully !")
with open("song1", "r+", encoding="utf-8") as f1:
for line1 in f1:
print(line1)
print("Read file successfully !")
可是,这样一看,就是重复性很高的代码,可以定义一个函数写标记
def function1():
# defination函数方法的描述简介
print("Read file successfully !")
return 0
然后代码变可以简化为如下:
def function1():
# defination
print("Read file successfully !")
return 0
with open("song", "r+", encoding="utf-8") as f:
for line in f:
print(line)
function1()
with open("song1", "r+", encoding="utf-8") as f1:
for line1 in f1:
print(line1)
function1()
print("Read file successfully !")
with open("song2", "r+", encoding="utf-8") as f2:
for line2 in f2:
print(line2)
function1()
函数是什么?
函数一词来源于数学,但编程中的「函数」概念,与数学中的函数是有很大不同的,具体区别,我们后面会讲,编程中的函数在英文中也有很多不同的叫法。
在BASIC中叫做subroutine(子过程或子程序),在Pascal中叫做procedure(过程)和function,在C中只有function,在Java里面叫做method。
定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可
特性:
1,减少代码重复
2,使程序变得可扩展
3,使程序变得易维护
函数可以带参数(先定义函数,再调用)
def mothod1(x,y):
c = x * y
print(c)
return 0
mothod1(2,3)
函数参数与局部变量
形参变量只有在被调用时才分配内存单元,在调用结束时,即刻释放所分配的内存单元。因此,形参只在函数内部有效。函数调用结束返回主调用函数后则不能再使用该形参变量
实参可以是常量、变量、表达式、函数等,无论实参是何种类型的量,在进行函数调用时,它们都必须有确定的值,以便把这些值传送给形参。因此应预先用赋值,输入等办法使参数获得确定值
上面的额介绍的函数中x,y便是形参,2,3便是实参。
默认参数
看下面的代码:
def register(name,age,sex,company):
#注册信息
print("----------员工信息注册----------")
print("name : ",name)
print("age : ",age)
print("sex : ",sex)
print("company : ",company)
return 0
register("dandy", "18", "male", "alibaba")
register("claire", "17", "female", "alibaba")
register("harden", "19", "male", "alibaba")
register("paul", "20", "male", "alibaba")
一眼就能看出来,这都是你来自一家公司的,即使不都是我们也能设置一个默认的公司,这就是默认参数的作用
def register(name,age,sex,company = ‘alibaba‘):
如此,可以只输入3个参数,最后一个不输入默认为“alibaba”
另外,我们将company当做默认参数的时候一定要将它,置于末尾。
关键参数
正常情况下,给函数传参数要按顺序,不想按顺序就可以用关键参数,只需指定参数名即可,但记住一个要求就是,关键参数必须放在位置参数之后。
stu_register(age=22,name=‘dandy‘,course="python",)
非固定参数
若你的函数在定义时不确定用户想传入多少个参数,就可以使用非固定参数
def stu_register(name,age,*args): # *args 会把多传入的参数变成一个元组形式
print(name,age,args)
stu_register("dandy",22)
#输出
#dandy 22 () #后面这个()就是args,只是因为没传值,所以为空
stu_register("Jack",32,"CN","Python")
#输出
# Jack 32 (‘CN‘, ‘Python‘)
再介绍下**kwargs
def stu_register(name,age,**kwargs): # **kwargs会把多传入的参数变成一个元组形式
print(name,age,kwargs)
stu_register("dandy",22)
#输出
#dandy 22 () #后面这个()就是kwargs,只是因为没传值,所以为空
stu_register("Jack",32,"CN","Python",sex="Male",province="ShanDong")
#输出
# Jack 32 (‘CN‘, ‘Python‘) {‘province‘: ‘ShanDong‘, ‘sex‘: ‘Male‘}
局部变量与全局变量
name = "dandy" def change_name(name): print("before change :>>>",name) name = "claire" print("after change:>>>",name) change_name(name) print("who am I ? >>>",name)
结果 before change :>>> dandy after change:>>> claire who am I ? >>> dandy
返回值
要想获取函数的执行结果,就可以用return语句把结果返回
注意:
- 函数在执行过程中只要遇到return语句,就会停止执行并返回结果,so 也可以理解为 return 语句代表着函数的结束
- 如果未在函数中指定return,那这个函数的返回值为None
递归
在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
def cal1(n):
print(n)
if(n/2)== 0:
return n
return cal1(int(n/2))
cal1(11)
运行结果
11
5
2
1
0
递归特性:
1. 必须有一个明确的结束条件
2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少
3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)
堆栈扫盲http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html
函数式编程介绍
函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计。函数就是面向过程的程序设计的基本单元。
函数式编程中的函数这个术语不是指计算机中的函数(实际上是Subroutine),而是指数学中的函数,即自变量的映射。也就是说一个函数的值仅决定于函数参数的值,不依赖其他状态。比如sqrt(x)函数计算x的平方根,只要x不变,不论什么时候调用,调用几次,值都是不变的。
Python对函数式编程提供部分支持。由于Python允许使用变量,因此,Python不是纯函数式编程语言。
一、定义
简单说,"函数式编程"是一种"编程范式"(programming paradigm),也就是如何编写程序的方法论。
主要思想是把运算过程尽量写成一系列嵌套的函数调用。举例来说,现在有这样一个数学表达式:
(1 + 2) * 3 - 4
传统的过程式编程,可能这样写:
var a = 1 + 2;
var b = a * 3;
var c = b - 4;
函数式编程要求使用函数,我们可以把运算过程定义为不同的函数,然后写成下面这样:
var result = subtract(multiply(add(1,2), 3), 4);
这段代码再演进以下,可以变成这样
add(1,2).multiply(3).subtract(4)
这基本就是自然语言的表达了。再看下面的代码,大家应该一眼就能明白它的意思吧:
merge([1,2],[3,4]).sort().search("2")
因此,函数式编程的代码更容易理解。
要想学好函数式编程,不要玩py,玩Erlang,Haskell, 好了,我只会这么多了。。。
高阶函数
变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
def fun(a,b,f): c = f(a) + f(b) print(c) fun(9,-1,abs)
结果:10
Python基础3(2017-07-20)