色胃康胶囊 发表于 2018-8-12 10:49:20

我的python学习--第四天

  一、首先是对前三天的学习内容进行复习
  1、python基础的数据结构
  数字(int/float,包括整数和浮点数)
  布尔(boolean => True/False)
  字符串(str,使用''或""括起来)
  列表(list)
  列表是使用[]括起来的一组数组,在内存中是连续的,可以对其增删改查
  字典(dict)
  字典是使用{}括起来的k/v键值对,经过哈希计算随机分布在内存中,是无序的,可以对其增删改查
  元组(tuple)
  元组与列表类似,不同之处在于元组的元素不能修改,元组使用小括号()
  2、python的语法
  定义变量 a=1
  if else语句
  if 布尔值:
  True执行这里
  else:
  False执行这里
  for循环
  循环list或者dict
  while循环
  while 布尔值:
  布尔值真,一直执行
  break/continue
  调试方法(print)
  help()函数和dir()函数
  help()函数是查看函数或模块用途的详细说明,而dir()函数是查看函数或模块内的操作方法,输出的是 方法列表。
  3、list和dict的区别
  list有顺序
  查找、追加很快,插入、删除很慢,命中cpu缓存的概率大
  dict没顺序
  查找、修改、删除都很快
  dict->list : for key,value in dict.items()
  list转成dict : for index,value in enumerate(list)
  4、文件读取
  open:打开文件
  read、readline、readlines:读取文件内容
  write、writelines:文件写入
  close:关闭文件
  tell()和seek()
  文件刚打开时,只能在开始的位置,每次read、readline、readlines时都会移动指针到读取数据的地方
  tell():返回文件所在指针的当前位置
  seek(#,whence=0):从文件中移动#个文件指针,正数则往结束方向移动,负数则向开始方向移动,如果设定了whence参数,就以whence设定的起始位置为准,0表示文件开始处、1表示当前位置、2表示文件结尾处
  二、对第三天的统计nginx访问日志,获取访问前十的ip地址,并用html的格式呈现的练习进行优化
#!/usr/bin/python  
#coding:utf-8
  

  
res = {}
  
'''
  
f = open('access.log')                           # 优化前的文件开启,关闭
  
...
  
f.close()
  
'''
  
with open('access.log') as f:                      # 优化后的文件开启,关闭
  
    for line in f:
  
      tmp = line.split(' ')
  
      ip,url = tmp,tmp
  
      '''
  
      if (ip,url) in res:                        # 优化前的数据统计
  
            res[(ip,url)] += 1
  
      else:
  
            res[(ip,url)] = 1
  
      '''
  
      res[(ip,url)] = res.get((ip,url),0)+1      # 优化后的数据统计
  
res_list = res.items()
  
# print res_list
  

  
'''                                                # 优化前,使用冒泡法进行排序
  
for j in range(11):
  
    for i in range(len(res_list)-1):
  
      if res_list > res_list:
  
            res_list,res_list=res_list,res_list
  
'''
  

  
res_list = sorted(res_list,key=lambda x:x,reverse=True) # 优化后使用sorted函数排序
  

  
i = 0
  
html_str = '<table border="1px">'
  
# res_list.reverse()
  
for r in res_list[:10]:
  
    i = i+1
  
# (('218.200.66.204', '/data/uploads/2014/0707/12/small_53ba21ee5cbde.jpg'), 1),
  
    html_str += '<tr><td>No%s</td> <td>%s</td><td>%s</td><td>%s</td>'%(i,r,r,r)
  
html_str+='</table>'
  

  
html_f = open('res.html','w')
  
html_f.write(html_str)
  
html_f.close()
  三、函数(第四天重点)
  函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
  函数能提高应用的模块性,和代码的重复利用率。Python提供了许多内建函数,比如print()。但你也可以自己创建函数,这被叫做用户自定义函数。
  定义函数的规则:
  函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()。
  任何传入参数和自变量必须放在圆括号中间。圆括号中间可以用于定义默认参数。
  函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
  函数内容以冒号起始,并且缩进。
  return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。
  语法:
  def func_name(parameters):
  func_suite
  return
  示例:定义一个函数,实现阶乘
def f(num):  
    fact = 1
  
    if num<0:
  
      return "No negative factorial"
  
    elif num==0:
  
      return 1
  
    for i in range(1,num+1):
  
      fact *= i
  
    return fact
  参数:
  调用函数时使用的函数类型:
  必备参数:
  调用函数时,必须以正确的顺序传入,并且传入的参数必须与声明的参数一致
>>> def hello(name):  
...   return 'hello '+name
  
...
  
>>> hello('world')
  
'hello world'
  关键字参数:
  关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。
>>> def hello(name,age):  
...   return 'hello %s,your age is %s'%(name,age)
  
...
  

  
>>> hello(age=20,name='Alice')
  
'hello Alice,your age is 20'
  缺省参数:
  调用函数时,缺省参数的值如果没有传入,则使用预先定义的默认值。
>>> def hello(name,age=20):  
...   return 'hello %s,your age is %s'%(name,age)
  
...
  
>>> hello('Bob')
  
'hello Bob,your age is 20'
  不定长参数:
  你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数。
  *开头的参数,收集所有剩下的参数(位置参数),适用于元祖
  **开头的参数,收集所有剩下的参数(关键字参数),适用于字典
>>> def hello(name,*msg):  
...   return 'hello %s,your msg is %s'%(name,msg)
  
...
  
>>> hello('Catalina',20,'Female')
  
"hello Catalina,your msg is (20, 'Female')"
  匿名函数:
  lambda
  语法:lambda ]:expression
  示例:写一个函数,求两个数字之和
>>> sum = lambda x,y:x+y  
>>> print sum(10,5)
  
15
  作用域:
  一个程序的所有的变量并不是在哪个位置都可以访问的。访问权限决定于这个变量是在哪里赋值的。变量的作用域决定了在哪一部分程序你可以访问哪个特定的变量名称。函数内部变量,先在函数内部找,找不到才会去全局找,内部变量想修改为全局变量,只需用global声明一下。多个函数之间尽量避免使用全局变量
  示例:
#!/usr/bin/python  
#coding: utf-8
  

  
total = 0                                              #这是一个全局变量
  
def sum(arg1,arg2):
  
   total = arg1 + arg2                                 # total在这里是局部变量
  
   print "函数内是局部变量: ",total
  
   return total
  

  

  
sum(10,20)
  
print "函数外是全局变量: ",total
# python examp.py  
函数内是局部变量:30
  
函数外是全局变量:0
  将局部变量变为全局变量:
num = 100                                          # 全局变量  
def func():
  
    global num                                       # 使用global将局部变量定义为全局变量
  
    num = 200                                        # 局部变量
  
    print num
  

  
func()
  
print num
  结果:
# python examp3.py  
200
  
200
  四、使用函数对'二'中的练习进行改造
def oper_file(file_name):                            # 定义函数,根据访问数对ip、url排序  
    res = {}
  
    with open(file_name) as f:
  
      for line in f:
  
            tmp = line.split(' ')
  
            ip,url = tmp,tmp
  
            res[(ip,url)] = res.get((ip,url),0)+1
  
    return sorted(res.items(),key=lambda x:x,reverse=True)
  

  
def get_html(arr):                                 # 将排序后的数据写成html格式
  
    tmpl = '<tr><td>No%s</td> <td>%s</td><td>%s</td><td>%s</td></tr>'
  

  
    html_str = '<h1>IP COUNT TABLE</h1>'
  
    html_str += '<table border="1px">'
  
    html_str += tmpl%(' ','IP','URL','COUNT')
  

  
    for index,value in enumerate(arr[:10]):
  
      html_str += tmpl%(index,value,value,value)
  
    html_str+='</table>'
  
    return html_str
  

  
def start_operate(file_name):                        # 将html格式的数据写入文件
  
    res = oper_file(file_name)
  
    with open('res.html','w') as f:
  
      f.write(get_html(res))
  

  
start_operate('access.log')
  html文件效果图:

  五、使用函数,对第三天的用户注册,登录功能进行改造
#!/usr/bin/python  
#coding:utf-8
  

  
service = raw_input('which service you want to choose,register or login: ').strip()
  

  
def file():
  
    name_list = []
  
    with open('user.txt') as fo:
  
      for msg in fo:
  
            msg_name = msg.strip('\n').split(':')
  
            name_list.append(msg_name)
  
    return name_list
  

  
def test(arr):
  
    while True:
  
      name = raw_input('Please Input your name: ').strip()
  
      passwd = raw_input('Please Input your password: ').strip()
  
      repasswd = raw_input('Please Input your password again: ').strip()
  

  
      if not name:
  
            print 'Name can not be null'
  
            continue
  
      elif name in arr:
  
            print 'User already exist.'
  
            continue
  
      elif not passwd or passwd!=repasswd:
  
            print 'Wrong password'
  
            continue
  
      else:
  
            return name,passwd
  
            break
  

  
def write_in(name,passwd):
  
    with open('user.txt','a+') as fo:
  
      fo.write('%s:%s\n'%(name,passwd))
  
      print 'Registration completed'
  

  
def register():
  
    res = file()
  
    name,passwd = test(res)
  
    write_in(name,passwd)
  

  
def login():
  
    with open('user.txt') as fo:
  
      d = {}
  
      for user in fo:
  
            user_name = user.strip('\n').split(':')
  
            user_passwd = user.strip('\n').split(':')
  
            d = user_passwd
  
    return d
  

  
def judge(arr):
  
    while True:
  
      name = raw_input('Please input your name: ').strip()
  
      passwd = raw_input('Please input your passwd: ').strip()
  

  
      if not name:
  
            print 'Name can not be null'
  
            continue
  
      elif name not in arr:
  
            print 'No such user'
  
            continue
  
      elif not passwd or passwd!=arr:
  
            print 'Wrong password'
  
            continue
  
      else:
  
            print 'login successfully'
  
            break
  

  
def msg():
  
    if service=='login':
  arr = login()
  
   judge(arr)
  
    elif service=='register':
  register()
  
    else:
  print 'No other choice.'
  

  
msg()
  运行结果:
# python homework_04.py  
which service you want to choose,register or login: register
  
Please Input your name: hello
  
Please Input your password: 1234
  
Please Input your password again: 1234
  
Registration completed
  
# python homework_04.py
  
which service you want to choose,register or login: login
  
Please input your name: hello
  
Please input your passwd: 1234
  
login successfully
页: [1]
查看完整版本: 我的python学习--第四天