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 = f.read()
print(data)#读取全部内容 f.close()#关闭文件

  输出结果

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 = 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语句把结果返回

  注意:

    1. 函数在执行过程中只要遇到return语句,就会停止执行并返回结果,so 也可以理解为 return 语句代表着函数的结束
    2. 如果未在函数中指定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)的更多相关文章

  1. 《Python基础教程》第20章学习笔记

    python实现:https://github.com/captainwong/instant_markup c++实现:https://github.com/captainwong/instant_ ...

  2. python基础教程2第20章 项目1:即时标记

    simple_markup.py import sys, re from util import * print('<html><head><title>...&l ...

  3. 【python基础】第07回 运算符和流程控制 2

    本章内容概要 1.逻辑运算符补充 2.循环结构 本章内容详解 1.逻辑运算符补充 两边都不为0的情况 or 直接取前面的值 and 直接取后面的值如果存在0的情况 and 直接取0 or 直接取非0 ...

  4. python基础全部知识点整理,超级全(20万字+)

    目录 Python编程语言简介 https://www.cnblogs.com/hany-postq473111315/p/12256134.html Python环境搭建及中文编码 https:// ...

  5. python最全学习资料:python基础进阶+人工智能+机器学习+神经网络(包括黑马程序员2017年12月python视频(百度云链接))

    首先用数据说话,看看资料大小,达到675G 承诺:真实资料.不加密,获取资料请加QQ:122317653 包含内容:1.python基础+进阶+应用项目实战 2.神经网络算法+python应用 3.人 ...

  6. 二十. Python基础(20)--面向对象的基础

    二十. Python基础(20)--面向对象的基础 1 ● 类/对象/实例化 类:具有相同属性.和方法的一类人/事/物 对象(实例): 具体的某一个人/事/物 实例化: 用类创建对象的过程→类名(参数 ...

  7. Python基础教程 - Tdcqma

      1.1 普通字符串 1.21 错误与异常 1.41 XXXXXX 1.61 XXXXXX 1.81 XXXXXX 1.101 XXXXXX 1.2 转义字符串 1.22 装饰器         1 ...

  8. (路-莫)-Python基础一

    一,Python介绍 1,python的出生与应用 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆(中文名字:龟叔)为了在阿姆斯特丹打 ...

  9. 十八. Python基础(18)常用模块

    十八. Python基础(18)常用模块 1 ● 常用模块及其用途 collections模块: 一些扩展的数据类型→Counter, deque, defaultdict, namedtuple, ...

  10. 第一篇:python基础

    python基础   python基础 本节内容 python起源 python的发展史 为什么选择python3 第一个python程序 变量定义 表达式和运算符 用户输入 流程控制 判断 流程控制 ...

随机推荐

  1. Vue中data返回对象和返回值的区别

    速记:粗浅的理解是,事件的结果是影响单个组件还是多个组件.因为大部分组件是要共享的,但他们的data是私有的,所以每个组件都要return一个新的data对象 返回对象的时候 <!DOCTYPE ...

  2. python基础-守护进程、守护线程、守护非守护并行

    守护进程 1.守护子进程 主进程创建守护进程  其一:守护进程会在主进程代码执行结束后就终止  其二:守护进程内无法再开启子进程,否则抛出异常:AssertionError: daemonic pro ...

  3. operation=

    x+=xxx 先执行xxx,再x=x+xxx 一个与之的问题 C(n,n/2) for (i=n;i>n/2;i--)        v*=i/(n+1-i);每次先执行i/(n+1-i),然后 ...

  4. C 线程学习记录

    "互斥锁"(Mutual exclusion,缩写 Mutex),防止多个线程同时读写某一块内存区域. 这时的解决方法,就是在门口挂n把钥匙.进去的人就取一把钥匙,出来时再把钥匙挂 ...

  5. java的抽象方法

    抽象类所起的功能就像定义模板的功能,子类必须继承抽象类,因此不能用final修饰 http://blog.csdn.net/wei_zhi/article/details/52736350 抽象类的函 ...

  6. Codeforces Round #523 (Div. 2) D. TV Shows

    传送门 https://www.cnblogs.com/violet-acmer/p/10005351.html 题意: 有n个节目,每个节目都有个开始时间和结束时间. 定义x,y分别为租电视需要的花 ...

  7. 当我new class的时候,提示以下错误: Unable to parse template "Class" Error message: This template did not produce a Java class or an interface Error parsing file template: Unable to find resource 'Package Header.j

    你肯定修改过class的template模板,改回去就好了 #if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")packag ...

  8. mac java_home等系统参数配置

    JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/HomeCLASSPAHT=.:$JAVA_HOME/lib ...

  9. IIS 错误:处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler”

    导致这种问题的原因是ASP.NET没有成功注册到IIS中,很有可能是先安装.Net Framework,然后安装IIS.为了避免此问题发生,要先安装IIS再安装.Net Framework. 解决方案 ...

  10. java中将string类型转int类型或者将string类型转long类型方法

    将字串 String 转换成整数 int 两种方法: 1).int i = Integer.parseInt("111"); 或 i = Integer.parseInt([Str ...