python学习

本文介绍了Python中的格式化打印、命令行参数处理、文件操作等实用技巧,并详细解释了常见语法如if __name__ == '__main__'的作用,还涉及了HTML转义字符处理及cmd模块的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2015-01-19

1.print是格式化打印

   -print "hello world"

   -print  “ %d is year"  %  year

   -strHello = "the length of (%s) is %d" %('laowangpython',len('laowangpython'))
    print strHello

   -print ("%.3s " % ("python"))
     pyt

   -print ("%.*s" % (4,"python"))
    pyth

   print 自动换行  :print 会自动在行末加上回车,如果不需回车,只需在print语句的结尾添加一个逗号”,“,就可以改变它的行为。

<span class="kw1">  >>> for i in range(0,6):
      print (i,)</span>

 

2. if __name__ == '__main__': 的解析

    每个.py文件都是一个模块,每个模块都有一个__name__的属性,在本模块内,它默认是'__main__',但是如果在另外一个.py文件B里面import 该模块,那么调用这个模块的时 候里面的__name__就不是'__main__'了。。所以为了在B里面调用这个模块的时候,仅仅把整个代码import过来,调用里面的函数,但是不执行模块里面需要执行的部分,所以使用这样的if语句,把该模块里面需要执行的部分放进去。。仅仅在该模块执行的时候执行,不影响其他调用该模块的.py文件

 

3.  或与非: or, and, not

 

4. int(year)   转化为整型

 

5. from __future__ import division  输入浮点数

6. # _*_ coding: utf-8 _*_     or  #coding=utf-8  解决中文解析

7.import os

   from os import listdir

   import os as o

   from oswalk import *   这样就可以使用oswalk文件里面的所有函数了,直接调用

 

8.os模块处理文件和目录

  listdir(”/")  列出目录下的文件和目录       windows下面使用d:\\ 进行分区指定

  walk  列出目录下整个信息,包括子目录

   os.walk,  os.path.walk ---后者产生3个列表信息:   路径,目录列表,文件列表 

      eg: for path, dirs., files in os.path.walk("/")

                        print root, dirs., files

 

9.文件操作:

   f=open(path,mode )   读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
   f.read([size]) size未指定则返回整个文件,如果文件大小>2倍内存则有问题.f.read()读到文件尾时返回""(空字串) ----read()之后,指针会移动到当前位置

   f.readline() 返回一行

   f.readline([size]) 返回包含size行的列表,size 未指定则返回全部行

   for line in f: print line #通过迭代器访问

   f.write("hello\n") #如果要写入字符串以外的数据,先将他转换为字符串.

  f.tell() 返回一个整数,表示当前文件指针的位置(就是到文件头的比特数).

  f.seek(偏移量,[起始位置])

     用来移动文件指针

      偏移量:单位:比特,可正可负

     起始位置:0-文件头,默认值;1-当前位置;2-文件尾

f.close() 关闭文件

 

9-2:python按行读取文件:

      1. while 1:                效率低,节省内存

              line=f.readline()

             if not line: break

       2. import fileinput               效率低

           for line infileinput.input("sample.txt"):       

       3. while 1:        效率高

               lines=f.readlines()

               if not lines: break

               for line in lines:

        4. file对象

              for line in open(file,mode)

 

 

10 出错:IndentationError:expected an indented block错误解决----需要缩进

 

11. python 处理html里面的转义字符:

      抓网页数据经常遇到例如&gt;或者&nbsp;这种HTML转义符,抓到字符串里很是烦人。

     比方说一个从网页中抓到的字符串

   html = '&lt;abc&gt;'

     用Python可以这样处理:

  import HTMLParser
  html_parser = HTMLParser.HTMLParser()
  txt = html_parser.unescape(html) #这样就得到了txt = '<abc>'

    如果还想转回去,可以这样:

  import cgi
  html = cgi.escape(txt) # 这样又回到了 html = '&lt;abc&gt'

 

12 python处理命令行参数

     1.sys.argv[] 是所有的命令行参数列表,sys.argv[1]是脚本名字

     2.对于其他的参数解析可以使用getopt模块

         import sys,getopt

         try:  

             opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help""output="])  ----1.除脚本名之后的命令行所有选项和参数;2.短命令集合  3.长命令集合

        except getopt.GetoptError:  

            # print help information and exit:

 

        函数返回两个列表:opts 和args 。opts 为分析出的格式信息。args 为不属于格式信息的剩余的命令行参数。

        opts 是一个两元组的列表。每个元素为:( 选项, 参数) 。如果没有附加参数则为空串'' 。
        eg: '-h -o file --help --output=out file1 file2'

          在分析完成后,opts 应该是: [('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out')]
          而args 则为: ['file1', 'file2']

         接着使用循环来处理opts的合法性:

         for o, a in opts:  

             if o in ("-h""--help"):  

                    usage()  

                    sys.exit()  

          if o in ("-o""--output"):  

                    output = a 

 

       

 13. cmd 模块: http://blog.sina.com.cn/s/blog_ac9fdc0b0101nd3d.html

    

class PyCDC(cmd.Cmd):
    def __init__(self):       ---默认基类创建,类的成员变量在此函数内声明,可以赋初值
        cmd.Cmd.__init__(self)
        self.CDROM="e:\\training\\2014\\Python"
        self.CDDIR='e:\\training\\2014\\Python\\script'
        self.prompt="(PyCDC)>"                                             -----------cmd的promt是命令行前缀
        self.intro=''' PyCDC0.5 usage:                                    -----------cmd的intro是命令行的最初提示
              dir dirname #the save/search dir, default is ../
              walk filename # keep the cdc info to filename, use *.cdc
              find  keywork # search all .cdc files in the save/search dir, input the lines including the keyword
              ?  #seach  ------显示命令选择界面EOF walk  dir find 等这些函数(help_walk, do_walk 这些函数都是成对出现的)
              EOF # exit the system
              '''
            
    def help_EOF(self): 
        print "exit the programme"
    def do_EOF(self, line):
        sys.exit()
       
    def help_walk(self):
        print "walk cd and export inot *.cdc"
    def do_walk(self,filename):

        if filename == "":
            filename=raw_input("input the cdc filename::")
            print "walk the cdc to : %s" % filename
            osWalk(self.CDROM, os.path.join(self.CDDIR,filename))  ----成员函数里面的参数使用类的属性成员self.xx

                                                                                                        ----成员函数里面调用其他模块的函数

 

     cdc=PyCDC()

      cdc.cmdloop()- --这个函数执行cmd模块的命令界面,可以根据函数名里面的关键词(do_walk)walk选择,来执行do_walk函数

   

     

14. 类的使用 

      filename="xxx"

    类成员函数使用:cdc.do_walk(filename) ,第一个参数self省略

 

15 in是非常强大 匹配操作, 可以判断字符串,list ,元组,字典中的元素是否存在,对于字符串就是匹配操作了

    a='12345'

    if  '1' in a

 

16.所有python软件都可以通过python setup.py install来安装

 

17.利用chardet来将文本解析为utf8格式,支持中文  *******字符编码问题*************

1 import chardet
2 def _smartcode(stream):
3     """smart recove stream into UTF-8
4     """
5     ustring = stream
6     codedetect = chardet.detect(ustring)["encoding"]
7     print codedetect
8     try:
9         print ustring
10         ustring = unicode(ustring, codedetect)
11         print ustring
12         return "%s %s"%("",ustring.encode('utf8'))
13     except:
14         return u"bad unicode encode try!"

 

18.python文档化开发---开发规范

     epydoc文档生成工具 (

在cygwin下安装 svn co https://epydoc.svn.sourceforge.net/svnroot/epydoc/trunk/epydoc epydoc

 python setup.py install

 然后使用 epydoc --config cdc.cfg 可以在api docs目录(mv *docs docs,否则没法打开)看到生成的html文件

不同系统上的安装:http://web.mit.edu/course/6/6.863/src/epydoc-3.0.1/doc/manual-install.html

(windows上面安装.exe之后,在python目录下面的script目录会生成epydoc.pyw界面)

       http://blog.youkuaiyun.com/largetalk/article/details/6950435

http://blog.youkuaiyun.com/agoago_2009/article/details/28415301

 

19:命名规范

      命令尽量使用动宾短语

      目录 文件名全部小写

       类名使用首字母大写单词串(eg:WikiNames)

       全局变量使用全大写字串(eg:CAPWORD)

      函数使用混合大小写串(eg:mixCase)

       内部变量 常数,全部小写

       eg:

        1 from mypacket import MyClass
        2 GLOBALVAR="是也乎"
        3 def doInsert(arg):
        4         MyClass.myFunc(GLOBALVAR)

 

 

20.对于一个列表hello=['a','b','c'],想要它们换行输出  print '\n'.join(hello)

21. python包的安装, python  setup.py  install

22. 使用pip 工具来安装python 包:

      1. wget https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz

         easy_install pip

      2. curl -0 https://raw.github.com/pypa/pip/master/contrib/get-pip.py

          sudo python get-pip.py

     pip install Markdown

     pip install -U Markdown

     pip uninstall Markdown

     pip search "Markdown"

 

 

 

 

 

 

 

 

 

 

 

***针对cd管理:

http://tech.sina.com.cn/c/2003-12-05/25149.html

http://www.nicomsoft.com/products/ocr/features/类似通过抓取指定介质的信息进行外部管理的软件是一个大类,cdc dialog

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值