Python 编程中常用的12 种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序、去重,字典排序,字典、列表、字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进制转换,Python 调用系统命令或者脚本,Python 读写文件。

1、正则表达式替换

目标: 将字符串 line 中的 overview.gif 替换成其他字符串

  1. >>> line = '<IMG ALIGN="middle" SRC=\'#\'" /span>

  2. >>> mo=re.compile(r'(?<=SRC=)"([\w+\.]+)"',re.I)  

  3. >>> mo.sub(r'"\1****"',line)  

  4. '<IMG ALIGN="middle" SRC=\'#\'" /span>

  5. >>> mo.sub(r'replace_str_\1',line)  

  6. '<IMG ALIGN="middle" replace_str_overview.gif BORDER="0" ALT="">'< /span>

  7. >>> mo.sub(r'"testetstset"',line)  

  8. '<IMG ALIGN="middle" SRC=\'#\'" /span>

注意: 其中 \1 是匹配到的数据,可以通过这样的方式直接引用

2、遍历目录方法

在某些时候,我们需要遍历某个目录找出特定的文件列表,可以通过os.walk方法来遍历,非常方便

  1. import os

  2. fileList = []

  3. rootdir = "/data"

  4. for root, subFolders, files in os.walk(rootdir):

  5. if '.svn' in subFolders: subFolders.remove('.svn')  # 排除特定目录

  6. for file in files:

  7.  if file.find(".t2t") != -1:# 查找特定扩展名的文件

  8.      file_dir_path = os.path.join(root,file)

  9.      fileList.append(file_dir_path)  

  10. print fileList

3、列表按列排序(list sort)

如果列表的每个元素都是一个元组(tuple),我们要根据元组的某列来排序的话,可参考如下方法

下面例子我们是根据元组的第2列和第3列数据来排序的,而且是倒序(reverse=True)

  1. >>> a = [('2011-03-17', '2.26', 6429600, '0.0'), ('2011-03-16', '2.26', 12036900,'-3.0'),

  2. ('2011-03-15', '2.33', 15615500,'-19.1')]

  3. >>> print a[0][0]

  4. 2011-03-17

  5. >>> b = sorted(a, key=lambda result: result[1],reverse=True)

  6. >>> print b

  7. [('2011-03-15', '2.33', 15615500, '-19.1'), ('2011-03-17', '2.26', 6429600, '0.0'),

  8. ('2011-03-16', '2.26', 12036900, '-3.0')]

  9. >>> c = sorted(a, key=lambda result: result[2],reverse=True)

  10. >>> print c

  11. [('2011-03-15', '2.33', 15615500, '-19.1'), ('2011-03-16', '2.26', 12036900, '-3.0'),

  12. ('2011-03-17', '2.26', 6429600, '0.0')]

4、列表去重(list uniq)

有时候需要将list中重复的元素删除,就要使用如下方法

  1. >>> lst= [(1,'sss'),(2,'fsdf'),(1,'sss'),(3,'fd')]

  2. >>> set(lst)

  3. set([(2, 'fsdf'), (3, 'fd'), (1, 'sss')])

  4. >>>

  5. >>> lst = [1, 1, 3, 4, 4, 5, 6, 7, 6]

  6. >>> set(lst)

  7. set([1, 3, 4, 5, 6, 7])

5、字典排序(dict sort)

一般来说,我们都是根据字典的key来进行排序,但是我们如果想根据字典的value值来排序,就使用如下方法

  1. >>> from operator import itemgetter

  2. >>> aa = {"a":"1","sss":"2","ffdf":'5',"ffff2":'3'}

  3. >>> sort_aa = sorted(aa.items(),key=itemgetter(1))

  4. >>> sort_aa

  5. [('a', '1'), ('sss', '2'), ('ffff2', '3'), ('ffdf', '5')]

从上面的运行结果看到,按照字典的value值进行排序的

6、字典,列表,字符串互转

以下是生成数据库连接字符串,从字典转换到字符串

  1. >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}

  2. >>> ["%s=%s" % (k, v) for k, v in params.items()]

  3. ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']

  4. >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])

  5. 'server=mpilgrim;uid=sa;database=master;pwd=secret'

下面的例子 是将字符串转化为字典

  1. >>> a = 'server=mpilgrim;uid=sa;database=master;pwd=secret'

  2. >>> aa = {}

  3. >>> for i in a.split(';'):aa[i.split('=',1)[0]] = i.split('=',1)[1]

  4. ...

  5. >>> aa

  6. {'pwd': 'secret', 'database': 'master', 'uid': 'sa', 'server': 'mpilgrim'}

7、时间对象操作

  1. 将时间对象转换成字符串

  2. >>> import datetime

  3. >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

  4.  '2011-01-20 14:05'

  5. 时间大小比较

  6. >>> import time

  7. >>> t1 = time.strptime('2011-01-20 14:05',"%Y-%m-%d %H:%M")

  8. >>> t2 = time.strptime('2011-01-20 16:05',"%Y-%m-%d %H:%M")

  9. >>> t1 > t2

  10.  False

  11. >>> t1 < t2

  12.  True

  13. 时间差值计算,计算8小时前的时间

  14. >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

  15.  '2011-01-20 15:02'

  16. >>> (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M")

  17.  '2011-01-20 07:03'

  18. 将字符串转换成时间对象

  19. >>> endtime=datetime.datetime.strptime('20100701',"%Y%m%d")

  20. >>> type(endtime)

  21.  <type 'datetime.datetime'>

  22. >>> print endtime

  23.  2010-07-01 00:00:00

  24. 将从 1970-01-01 00:00:00 UTC 到现在的秒数,格式化输出  

  25. >>> import time

  26. >>> a = 1302153828

  27. >>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(a))

  28.  '2011-04-07 13:23:48'

8、命令行参数解析(getopt)

通常在编写一些运维脚本时,需要根据不同的条件,输入不同的命令行选项来实现不同的功能 在Python中提供了getopt模块很好的实现了命令行参数的解析,下面距离说明。请看如下程序:

  1. #!/usr/bin/env python

  2. # -*- coding: utf-8 -*-

  3. import sys,os,getopt

  4. def usage():

  5. print '''''

  6. Usage: analyse_stock.py [options...]

  7. Options:

  8. -e : Exchange Name

  9. -c : User-Defined Category Name

  10. -f : Read stock info from file and save to db

  11. -d : delete from db by stock code

  12. -n : stock name

  13. -s : stock code

  14. -h : this help info

  15. test.py -s haha -n "HA Ha"

  16. '''

  17. try:

  18. opts, args = getopt.getopt(sys.argv[1:],'he:c:f:d:n:s:')

  19. except getopt.GetoptError:

  20. usage()

  21. sys.exit()

  22. if len(opts) == 0:

  23. usage()

  24. sys.exit()  

  25. for opt, arg in opts:

  26. if opt in ('-h', '--help'):

  27.  usage()

  28.  sys.exit()

  29. elif opt == '-d':

  30.  print "del stock %s" % arg

  31. elif opt == '-f':

  32.  print "read file %s" % arg

  33. elif opt == '-c':

  34.  print "user-defined %s " % arg

  35. elif opt == '-e':

  36.  print "Exchange Name %s" % arg

  37. elif opt == '-s':

  38.  print "Stock code %s" % arg

  39. elif opt == '-n':

  40.  print "Stock name %s" % arg  

  41. sys.exit()

9、print 格式化输出

9.1、格式化输出字符串

截取字符串输出,下面例子将只输出字符串的前3个字母

>>> str="abcdefg"

>>> print "%.3s" % str

abc

按固定宽度输出,不足使用空格补全,下面例子输出宽度为10

>>> str="abcdefg"

>>> print "%10s" % str

abcdefg

截取字符串,按照固定宽度输出

>>> str="abcdefg"

>>> print "%10.3s" % str

abc

浮点类型数据位数保留

>>> import fpformat

>>> a= 0.0030000000005

>>> b=fpformat.fix(a,6)

>>> print b

0.003000

对浮点数四舍五入,主要使用到round函数

>>> from decimal import *

>>> a ="2.26"

>>> b ="2.29"

>>> c = Decimal(a) - Decimal(b)

>>> print c

-0.03

>>> c / Decimal(a) * 100

Decimal('-1.327433628318584070796460177')

>>> Decimal(str(round(c / Decimal(a) * 100, 2)))

Decimal('-1.33')

9.2、进制转换

有些时候需要做不同进制转换,可以参考下面的例子(%x 十六进制,%d 十进制,%o 八进制)

  1. >>> num = 10

  2. >>> print "Hex = %x,Dec = %d,Oct = %o" %(num,num,num)

  3.  Hex = a,Dec = 10,Oct = 12

10、Python调用系统命令或者脚本

  1. 使用 os.system() 调用系统命令 , 程序中无法获得到输出和返回值

  2. >>> import os

  3. >>> os.system('ls -l /proc/cpuinfo')

  4. >>> os.system("ls -l /proc/cpuinfo")

  5.  -r--r--r-- 1 root root 0  3月 29 16:53 /proc/cpuinfo

  6.  0

  7. 使用 os.popen() 调用系统命令, 程序中可以获得命令输出,但是不能得到执行的返回值

  8. >>> out = os.popen("ls -l /proc/cpuinfo")

  9. >>> print out.read()

  10.  -r--r--r-- 1 root root 0  3月 29 16:59 /proc/cpuinfo  

  11. 使用 commands.getstatusoutput() 调用系统命令, 程序中可以获得命令输出和执行的返回值

  12. >>> import commands

  13. >>> commands.getstatusoutput('ls /bin/ls')

  14.  (0, '/bin/ls')

11、Python 捕获用户 Ctrl+C ,Ctrl+D 事件

有些时候,需要在程序中捕获用户键盘事件,比如ctrl+c退出,这样可以更好的安全退出程序

  1. try:

  2.    do_some_func()

  3. except KeyboardInterrupt:

  4.    print "User Press Ctrl+C,Exit"

  5. except EOFError:

  6.    print "User Press Ctrl+D,Exit"

12、Python 读写文件

  1. 一次性读入文件到列表,速度较快,适用文件比较小的情况下

  2. track_file = "track_stock.conf"

  3. fd = open(track_file)

  4. content_list = fd.readlines()

  5. fd.close()

  6. for line in content_list:

  7.    print line  

  8. 逐行读入,速度较慢,适用没有足够内存读取整个文件(文件太大)

  9. fd = open(file_path)

  10. fd.seek(0)

  11. title = fd.readline()

  12. keyword = fd.readline()

  13. uuid = fd.readline()

  14. fd.close()  

  15. 写文件 write 与 writelines 的区别  

  16. Fd.write(str) : 把str写到文件中,write()并不会在str后加上一个换行符

  17. Fd.writelines(content) : 把content的内容全部写到文件中,原样写入,不会在每行后面加上任何东西

本文转载自公众号:「51CTO技术栈」

更多相关文章阅读


http://www.taodudu.cc/news/show-6409993.html

相关文章:

  • 特别编辑--windows+python+django实现前端页面上传到指定路径生成个性化二维码
  • Python大道至简(第七部分)
  • 求职记录
  • c语言求正方形内切圆面积公式,C语言已知内切圆半径求直角三角形的三条边长...
  • java并查集判断是否是连通图_并查集-判断图的连通
  • 算法笔记16.并查集
  • 看了必懂的并查集原理(转载)
  • 并查集讲解
  • 数据结构 | 第十一章:二叉树和其他树 | 【前序遍历】【中序遍历】【后序遍历】【层次遍历】 | 并查集
  • 通俗易懂超有爱的并查集~~~
  • 百度文库不能下载解决方案
  • 电脑快捷键大全- -
  • Windows电脑键盘快捷键大全【最全的快捷键】
  • 电脑快捷键汇总
  • 电脑(Windows)常用快捷键
  • linux 安装 openvpn
  • 连接HTB平台openvpn失败
  • openVPN服务端搭建
  • 中科大日常交流英语期末考试话题汇总
  • 2022年中考英语作文热点话题终极押题(附范文及详解)
  • 英语口语八十之[如何聊电影话题]
  • 英语口语——情景话题类词汇汇总
  • 英语话题 Health
  • 英语话题 topic 7:cooking
  • 2021考研英语大作文写作必备15个话题
  • 【gflags 】google gflags 使用方法
  • google 工具 gflags
  • gulp---
  • spiral grid
  • Google Guava Splitter

Python 编程中常用的12种基础知识总结相关推荐

  1. python编程中常用的12种基础知识总结

    python编程中常用的12种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序.去重,字典排序,字典.列表.字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进 ...

  2. python编程基础知识点总结_【转载】Python编程中常用的12种基础知识总结

    Python编程中常用的12种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序.去重,字典排序,字典.列表.字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进 ...

  3. python中 12_python编程中常用的12种基础知识总结

    1.正则表达式替换 目标: 将字符串line中的 overview.gif 替换成其他字符串 >>> line =' >>> mo=re.compile(r'(?& ...

  4. python文本字符分析、编写程序接收字符串_python 文本分析Python编程中字符串和列表的基本知识讲解...

    Python 字符串 字符串是 Python 中最常用的数据类型.我们可以使用引号来创建字符串. 创建字符串很简单,只要为变量分配一个值即可.例如: var1 = 'Hello World!' var ...

  5. 列举python中常用的数据类型_Python基础知识 变量和简单数据类型

    在本章节中,将介绍Python程序中会使用到的各种数据类型,以及如何在程序中使用变量来表示这些数据.其中用到的一些例子均来自<Python编程从入门到实践 第2版>. 一.变量 1. 变量 ...

  6. Python编程:从入门到实践(基础知识)

    第一章 起步 计算机执行源程序的两种方式: 编译:一次性执行源代码,生成目标代码 解释:随时需要执行源代码 源代码:采用某种编程语言编写的计算机程序 目标代码:计算机可执行,101010 编程语言分为 ...

  7. python的知识点运用_程序猿在Python编程中不得不使用的十二种基础知识

    Python编程中常用的12种基础知识,其中肯定有你不会的! 人生苦短,我用Python 1.正则表达式替换 目标: 将字符串line中的 overview.gif 替换成其他字符串. 人生苦短,我用 ...

  8. python编程的基本方法有哪些_Python编程中常用的基础知识有哪些?

    今天小编要跟大家分享的文章是关于Python编程中常用的基础知识有哪些?正在从事Python相关工作的小伙伴们,来和小编一起看一看本篇文章,希望本篇文章能够对大家有所帮助. 1.正则表达式替换 目标: ...

  9. python中常用的九种预处理方法

    本文总结的是我们大家在python中常见的数据预处理方法,以下通过sklearn的preprocessing模块来介绍; 1. 标准化(Standardization or Mean Removal ...

最新文章

  1. 剑指offer:矩阵中的路径
  2. aspen plus大小_AspenPlus
  3. LiveVideoStack线上分享第三季(八):移动视频工厂 - 如何实现“快速、灵活、简单的视频剪辑框架...
  4. android 打印机蜂鸣器,CANON喷墨打印机 蜂鸣器响5声不打印的问题解决办法
  5. 【渝粤题库】陕西师范大学700004 植物生理学
  6. 正则表达式学习笔记,电话号码、电子邮件、汉字、数字、字母的筛选
  7. 超声声场模拟_3D打印全息透镜聚焦超声在低成本脑成像中的应用
  8. 显著性测试(Friedman test, Post-hoc Nimenyi test以及可视化)
  9. 读书笔记:《浪潮之巅》
  10. 多用组合少用继承的设计模式JAVA_结合设计模式理解多用组合少用继承的原则(转)...
  11. 腾讯云主机SSH连接不上如何解决
  12. 全国计算机等级考试三级网络技术选择题考点
  13. kermit config files
  14. 【Wireshark系列十】wireshark怎么抓包、wireshark抓包详细图文教程
  15. 腾讯Android自动化测试实战
  16. [5] Java中的static关键字
  17. 求职者该如何理清自身的求职策略?
  18. 详解开发、实施、运维的区别
  19. Pytorch Random Erasing
  20. FBI针对Tor网络的恶意代码分析

热门文章

  1. 个股期权交易系统为什么和私密机构紧密相连?
  2. TMF容器使用iTouch运行就报错的问题
  3. Android MediaPlayer播放视频详细步骤
  4. 英文版-每一天-day by day and with each passing momment
  5. Ubuntu Linux环境搭建|系统篇
  6. 【Proverif语法学习(一)】
  7. GTX/GTH/GTY/GTP/GTZ/GTM有什么区别?
  8. Android 阿里推送正常推送以及辅助通道走过的坑,字节跳动+阿里+华为+腾讯等大厂Android面试题
  9. 各种jar下载 Jar File Download
  10. 步进电机的名词概念解析