专注于自动化测试,性能测试.......

发布新日志

  • 使用Python读取xml格式的测试数据(原创)

    2009-09-18 05:20:17

      python解析xml有两种模式:SAX和DOM模式,我使用的是DOM模式。

    测试数据的XML格式:

      <?xml version="1.0" encoding="utf-8" ?>
    - <DataPool>
    - <DataSheet id="01" name="ryxx">
    - <DataField id="001" name="xm">
      <Data id="0001">姓名1</Data>
      <Data id="0002">姓名2</Data>
      <Data id="0003">姓名3</Data>
      </DataField>
    - <DataField id="002" name="xb">
      <Data id="0001"></Data>
      <Data id="0002"></Data>
      </DataField>
      </DataSheet>
    - <DataSheet id="02" name="book">
    - <DataField id="001" name="bookname">
      <Data id="0001">《C#入门经典》</Data>
      </DataField>
      </DataSheet>
      </DataPool>

    读取测试数据的代码:

    #-*-coding:gb2312-*-
    from xml.dom import minidom
    class Data(object):
        #初始化时,指定要读取数据的Datasheet,以及路径
        def __init__(self,sheetname,path):
            #sheet名称,相当于Excel的sheet
            self.sname = sheetname
            #xml的路径
            self.path = path
            #初始化,返回指定Datasheet的Node
            self.xmldoc  =  minidom.parse(self.path)
            xe = self.xmldoc.getElementsByTagName("DataSheet")
            for i in xe:
                if i.getAttribute("name")==self.sname:
                    self.sheet = i

        #读取数据的方法,通过字段名称以及位置来获取对应的值
        def getvalue(self,field,num):
            str = []
            for i in self.sheet.getElementsByTagName("DataField"):
                if i.getAttribute("name") ==field:
                    for n in i.getElementsByTagName("Data"):
                        str.append(n.childNodes[0].data)
            return str[num]
    ##       下面代码为另外一种实现方法,不过比较麻烦
    ##        for i in self.sheet.childNodes:
    ##            if i.nodeType == 1:
    ##                if i.getAttribute("name") == field:
    ##                    for x in i.childNodes:
    ##                        if x.nodeType == 1:
    ##                            str.append(x.childNodes[0].data)
    ##        return str[num]
    #获取数据实例
    d = Data("ryxx","D:\TestData.xml")
    print d.getvalue("xb",0)

     

  • 今天收到新买的测试书《测试有道-微软测试技术心得》

    2009-09-17 00:48:25

      该书是新近出版的一本测试书籍,购买它是因为书籍简介中说:该书介绍了一些微软内部使用的小工具,某些章节还是中英文对照的。正好最近在狂补英语,所以也就心动了。今天拿到书,粗略的读了一下,内容倒是涉及的比较多,但是都是很简略的,还没细读,看完后,可能会写一下读后感吧。

  • 使用python提取英文文章中的单词及出现的次数(原创)

    2009-09-15 19:06:09

      经常要读一些英文的文章,但文章中的生僻单词经常会影响阅读的速度和节奏,所以就像先把文章中所有的单词提取出来,然后找出自己不认识的单词进行预读和背诵。下边是使用python进行单词的提取。

        #-*-coding:gb2312-*-
    import re
    import string
    #输出结果
    f = open("D:\\result.txt","w")
    #输入文本
    r = open("D:\\input.txt","r")
    strs =r.read()
    #使用正则表达式,把单词提出出来,并都修改为小写格式
    s = re.findall("\w+",str.lower(strs))
    #去除列表中的重复项,并排序
    l = sorted(list(set(s)))
    #去除含有数字和符号,以及长度小于5的字符串
    for i in l:
        m = re.search("\d+",i)
        n = re.search("\W+",i)
        if not m and  not n and len(i)>4:
            f.write(i +" : "+str(s.count(i))+"\n")
    r.close()
    f.close()

  • TestComplete使用全局变量(原创)

    2009-09-13 22:51:16

                             

      在使用Testcomplete(以下简称TC)过程中,经常会在脚本或者Project之间传递变量值,但是VBS脚本的面向对象特性比较弱,很难通过传递类的属性来做到这一点。同时,vbs也没有Python的持久存储的功能。当然你可以把变量存储在本地实体文件中,但是这样的做法麻烦且效率也不高。TC给出了一种解决方案,那就是使用Variables对象。这个对象共有三种类型,分别为:project,project suite,network suite

    分别对应了不同的作用域,当前项目,当前项目集,站点集。

    创建variables有两种方式:

     1)通过编辑器进行可视化编辑

     2)通过脚本进行编辑

    下面我们分别进行讲解:

    编辑器进行编辑有可视化,便捷的优点,但是不够灵活。打开编辑器通过点击Projectproject SuiteNework Suite节点就可以打开,界面中主要有以下几项:

    Column

    Description

    Name

    变量名称

     

    Type

    变量的类型,分别为 Boolean,Double,Integer,ObjectString

    Default Value

    默认值,Object对象没有默认值,如果对默认值进行修改,会影响所有使用该项目的人

    Local Value

    当前变量值,这个值取决于当前打开项目的计算机,Object对象只能在运行时被设置。

    Category

    对变量进行分类,用于更好的管理变量,比如,对变量进行排序,分类

    Description

    变量的文字描述

     

    使用脚本对variables进行编辑具有灵活的特点。

     创建变量

       Project.Variables.Addvariable Name,Type   ---Name为变量名 Type为变量类型

     修改变量

       Project.Variables.Name = 变量值  ---Name为变量名

     获取变量的属性

      

    GetVariableCategory

    返回变量分类

    GetVariableDefaultValue

    返回变量默认值

    GetVariableDescription

    返回变量描述

    GetVariableName

    根据一个变量集合的索引值返回变量名称

    GetVariableType

    返回变量类型

    VariableCount

    返回变量的个数

    获取变量值

     Project.variables.Name    Or

     Project. .Variables.VariableByName(Name) ---Name为变量名

     

    删除变量

     Project.Variables.RemoveVariable   Name  ---Name为变量名

    PS:利用Python的持久存储也可以实现全局变量的存储,使用,分类以及排序。

  • Python生成COM组件(原创)

    2009-09-13 22:46:57

       经过一段对Python的使用,发现它确实是一门比较优秀的语言,语法简练,类库丰富且调用简单,在数据库,文本处理,网络编程方面都很棒。所以就一直想在实际工作中,确切地来说是现在正在进行的自动化测试使用Python,但是由于测试工具不支持python语言,所以没法直接在工具中使用。就考虑怎么在C#或者VBS中引用Python,一直没有太好的思路。偶然间阅读了《Python programming on win32,里面提到了把Python的类注册成为Com组件供VBDelphi实用的例子,顿时豁然开朗。

      下面就该书中Implementing COM Objects with Python章节进行分析,首先给出原文:

    Implementing COM Objects with Python

    In this section, we discuss how to implement COM objects using Python and a small sample of such an object. We also present some Visual Basic code that uses our Python implemented object.

    For this demonstration, you'll write a simple COM object that supports a number of string operations. As Visual Basic is somewhat lacking in the string-processing department where Python excels, it's a good candidate. The sample provides a COM object with a single method, SplitString() . This method has semantics identical to the standard Python function string.split(); the first argument is a string to split, and the second optional argument is a string holding the character to use to make the split. As you have no doubt guessed, the method won't do much more than call the Python string.split() function.

    There are two steps to implement COM objects in Python:

    • Define a Python class with the methods and properties you wish to expose.
    • Annotate the Python class with special attributes required by the PythonCOM framework to expose the Python class as a COM object. These annotations include information such as the objects ProgID, CLSID, and so forth.

    Python中实现COM对象有两个步骤:

    1.            定义你希望暴露的类的方法和属性

    2.            注解PythonCOM框架为了暴露python类所需的专用属性,其中包括对象ProgID,CLSID等等

    The following code shows a small COM server written in Python:

    # SimpleCOMServer.py - A sample COM server - almost as small as they come!

    #

    # We expose a single method in a Python COM object.

    class PythonUtilities:

        _public_methods_ = [ 'SplitString' ]

        _reg_progid_ = "PythonDemos.Utilities"

        # NEVER copy the following ID

        # Use "print pythoncom.CreateGuid()" to make a new one.

        _reg_clsid_ = "{41E24E95-D45A-11D2-852C-204C4F4F5020}"

       

        def SplitString(self, val, item=None):

            import string

            if item != None: item = str(item)

            return string.split(str(val), item)

     

    # Add code so that when this script. is run by

    # Python.exe, it self-registers.

    if __name__=='__main__':

        print "Registering COM server..."

        import win32com.server.register

        win32com.server.register.UseCommandLine(PythonUtilities)

    The bulk of the class definition is taken up by the special attributes:

    _public_methods_

    A list of all methods in the object that are to be exposed via COM; the sample exposes only one method, SplitString.

    一列包含所有需要暴露的类方法的列表

    _reg_progid_

    The ProgID for the new object, that is, the name that the users of this object must use to create the object.

    新对象的ProgID,该名称是所有调用Com,创建对象时必须用到的。

    _reg_clsid_

    The unique CLSID for the object. As noted in the source code, you must never copy these IDs, but create new ones using pythoncom.CreateGuid().

    对象的CLSID(独一无二的),你可以通过Pythoncom.CreateGuid()创建。

    Full details of these and other possible attributes can be found in Chapter 12.

    The SplitString() method is quite simple: it mirrors the behavior. of the Python string.split() function. A complication is that COM passes all strings as Unicode characters, so you must convert them to Python strings using the str() function. Note that in Python 1.6, it's expected that the string and Unicode types will be unified allowing the explicit conversions to be removed.

    The only thing remaining is to register the object with COM. As the comments in the code imply, you can do this by executing the code as a normal Python script. The easiest way to do this is to open the source file in PythonWin and use the Run command from the File menu. After running the script, the PythonWin interactive window should display:

    Registering COM server...

    Registered: PythonDemos.Utilities

    Finally, let's test the COM object. Use Visual Basic for Applications, which ships with both Microsoft Office and Microsoft Excel, and perform. the following steps:

    1. Start Microsoft Word or Microsoft Excel.
    2. Press ALT-F8 to display the macros dialog.
    3. Enter a name for the macro (e.g., TestPython) and select Create.
    4. The Visual Basic editor is displayed. In the editor, enter the following code:

    5.            Set PythonUtils = CreateObject("PythonDemos.Utilities")

    6.            response = PythonUtils.SplitString("Hello from VB")

    7.            for each Item in response

    8.              MsgBox Item

    nex

    Now run this code by pressing the F5 key. If all goes well, you should see three message boxes. The first one is shown in Figure 5.2.

    Just to be complete and help keep your registry clean, unregister your sample COM server. You do this by following the same process that registered the server, except specify --unregister as an argument to your script. A message is printed saying the object is unregistered.

    自己练习实现的例子:

    import win32com.server.register

    import pythoncom

    class MyFirstCom(object):

     

        _public_methods_ = ['Instring']

     

        _reg_progid_ ="Pythoncom.FirstCom"

     

        _reg_clsid_ = pythoncom.CreateGuid()

     

        def Instring(self,val,vals):

            if val in vals:

                return True

            else:

                return False

     

    if __name__ == "__main__":

        win32com.server.register.UseCommandLine(MyFirstCom)
  • Python操作SQL Server数据库(原创)

    2009-08-29 15:44:11

     

    Pymssqlpython用来连接Mssql的一个模块,包含两个扩展模块

    Pymssql 这是遵循DB-API标准的模块

    _mssql 是一个直接操作SQL Server的底层模块,它有很多有用的功能,但是不遵循DB-API标准。

     

    pymssqlCnx

     用于连接Mssql数据库

    你可以使用pymssql.connect()来初始化连接类。它允许如下的参数。

    dsn :连接字符串,主要用于与之前版本的pymssql兼容

    user :用户名

    password :密码

    trusted :布尔值, 指定是否使用windows身份认证登陆

    host : 主机名

    database :数据库

    timeout :查询超时

    login_timeout :登陆超时

    charset :数据库的字符集

    as_dict :布尔值,指定返回值是字典还是元组

    max_conn :最大连接数

     

    Method

    autocommit(status)

    布尔值, 指示是否自动提交事务,默认的状态是关闭的,如果打开,你必须调用commit()方法来提交事务。
    close()

    关闭连接
    cursor()

    Return a cursor object, that can be used to make queries and fetch results from the database.

    返回游标对象,用于查询和返回数据
    commit()

    提交事务。
    rollback()

    回滚事务

    pymssqlCursor

    用于从数据库查询和返回数据

    rowcount

    返回最后操作影响的行数。
    connection

    返回创建游标的连接对象
    lastrowid

    返回插入的最后一行
    rownumber

    返回当前数据集中的游标(通过索引)

     

    游标方法

    close()

    关闭游标


    execute(operation)

    执行操作
    execute(operation, params)

    执行操作,可以提供参数进行相应操作
    executemany(operation, params_seq)

    operation is a string and params_seq is a sequence of tuples (e.g. a list). Execute a database operation repeatedly for each element in parameter sequence.

    执行操作,Params_seq为元组
    fetchone()

    在结果中读取下一行


    fetchmany(size=None)

    在结果中读取指定数目的行
    fetchall()

    读取所有行


    nextset()

    游标跳转到下一个数据集
    __iter__(), next()

    These methods faciliate Python iterator protocol. You most likely will not call them directly, but indirectly by using iterators.
    setinputsizes(), setoutputsize()

    These methods do nothing, as permitted by DB-API specs.

     

     

    举例:

    #-*-coding:gb2312-*-

    import pymssql

    #数据库连接

    conn = pymssql.connect(host =".",database ="master",user="sa",password="1")

    #定义游标

    cur = conn.cursor()

    #执行指定的sql

    cur.execute("select * from dbo.bookshop")

    #游标读取第一行

    row = cur.fetchone()

    for i in range(2):

        if i ==2:

            print row[0]," ".ljust(10-len(row[0])," "),row[1]," ".ljust(20-len(row[1])," "),row[2]

        row = cur.fetchone()

     

    #关闭数据库连接

    conn.close()

     

    相关资源:

    http://pymssql.sourceforge.net/index.php

  • Sql语句之Having用法总结

    2009-08-28 00:09:25

     Having子句的一般应用场景:Group by分组后对某列的聚合函数进行条件过滤

    当同时含有where子句、group by 子句 、having子句及聚集函数时,执行顺序如下:

    执行where子句查找符合条件的数据;

    使用group by 子句对数据进行分组;

    对group by 子句形成的组运行聚集函数计算每一组的值;

    最后用having 子句去掉不符合条件的组。

    实例:


    create table bookshop
    (bookcategory varchar(100) not null,
     bookname varchar(100) not null,
     bookprice money not null)

    insert into bookshop values
    ('C#','C# Programming',45.00)

    insert into bookshop values
    ('C#','Learn C#',60.50)

    insert into bookshop values
    ('Python','Dive into Python',70)

    insert into bookshop values
    ('VBS','VBS Document',20.5)

    select * from bookshop

    select bookcategory,sum(bookprice) from bookshop
    group by bookcategory
    having count(bookprice)>100

    下面是来自百度百科的解释:

    having

      使用 HAVING 子句选择行
      HAVING 子句对 GROUP BY 子句设置条件的方式与 WHERE 子句和 SELECT 语句交互的方式类似。WHERE 子句搜索条件在进行分组操作之前应用;而 HAVING 搜索条件在进行分组操作之后应用。HAVING 语法与 WHERE 语法类似,但 HAVING 可以包含聚合函数。HAVING 子句可以引用选择列表中出现的任意项。
      下面的查询得到本年度截止到目前的销售额超过 $40,000 的出版商:
      USE pubs
      SELECT pub_id, total = SUM(ytd_sales)
      FROM titles
      GROUP BY pub_id
      HAVING SUM(ytd_sales) > 40000
      下面是结果集:
      pub_id total
      ------ -----------
      0877 44219
      (1 row(s) affected)
      为了确保对每个出版商的计算中至少包含六本书,下面示例使用 HAVING COUNT(*) > 5 消除返回的总数小于六本书的出版商:
      USE pubs
      SELECT pub_id, total = SUM(ytd_sales)
      FROM titles
      GROUP BY pub_id
      HAVING COUNT(pub_id) > 5
      下面是结果集:
      pub_id total
      ------ -----------
      0877 44219
      1389 24941
      (2 row(s) affected)
      理解应用 WHERE、GROUP BY 和 HAVING 子句的正确序列对编写高效的查询代码会有所帮助:
      WHERE 子句用来筛选 FROM 子句中指定的操作所产生的行。
      GROUP BY 子句用来分组 WHERE 子句的输出。
      HAVING 子句用来从分组的结果中筛选行。
      对于可以在分组操作之前或之后应用的搜索条件,在 WHERE 子句中指定它们更有效。这样可以减少必须分组的行数。应当在 HAVING 子句中指定的搜索条件只是那些必须在执行分组操作之后应用的搜索条件。
      Microsoft&reg; SQL Server™ 2000 查询优化器可处理这些条件中的大多数。如果查询优化器确定 HAVING 搜索条件可以在分组操作之前应用,那么它就会在分组之前应用。查询优化器可能无法识别所有可以在分组操作之前应用的 HAVING 搜索条件。建议将所有这些搜索条件放在 WHERE 子句中而不是 HAVING 子句中。
      以下查询显示包含聚合函数的 HAVING 子句。该子句按类型分组 titles 表中的行,并且消除只包含一本书的组:
      USE pubs
      SELECT type
      FROM titles
      GROUP BY type
      HAVING COUNT(type) > 1
      下面是结果集:
      type
      ------------------
      business
      mod_cook
      popular_comp
      psychology
      trad_cook
      (5 row(s) affected)
      以下是没有聚合函数的 HAVING 子句的示例。该子句按类型分组 titles 表中的行,并且消除不是以字母 p 开头的那些类型。
      USE pubs
      SELECT type
      FROM titles
      GROUP BY type
      HAVING type = '%p%'
      下面是结果集:
      type
      ------------------
      popular_comp
      psychology
      (2 row(s) affected)
      如果 HAVING 中包含多个条件,那么这些条件将通过 AND、OR 或 NOT 组合在一起。以下示例显示如何按出版商分组 titles,只包括那些标识号大于 0800、支付的总预付款已超过 $15,000 且销售书籍的平均价格小于 $20 的出版商。
      SELECT pub_id, SUM(advance) AS AmountAdvanced,
      AVG(price) AS AveragePrice
      FROM pubs.dbo.titles
      WHERE pub_id > '0800'
      GROUP BY pub_id
      HAVING SUM(advance) > 15000
      AND AVG(price) < 20
      ORDER BY 可以用来为 GROUP BY 子句的输出排序。下面的示例显示使用 ORDER BY 子句以定义返回 GROUP BY 子句中的行的顺序:
      SELECT pub_id, SUM(advance) AS AmountAdvanced,
      AVG(price) AS AveragePrice
      FROM pubs.dbo.titles
      WHERE pub_id > '0800'
      AND price >= 5
      GROUP BY pub_id
      HAVING SUM(advance) > 15000
      AND AVG(price) < 20
      ORDER BY pub_id DESC


     

  • 使用Python实现利用google翻译英文文章中的单词

    2009-08-27 23:16:30

    #-*-coding:gb2312-*-
    import urllib,urllib2
    from sgmllib import SGMLParser
    import re

    class URLLister(SGMLParser):

        def __init__(self):

            SGMLParser.__init__(self)

            self.result = []

            self.open = False

        def start_div(self, attrs):

            id = [v for k, v in attrs if k=='id']

            if 'result_box' in id:

                self.open = True

        def handle_data(self, text):

            if self.open:
                self.result.append(text)
                self.open = False

    #读取Txt文件中的英文文章并利用正则表达式解析单词

    f = open("D:\\result.txt","w")
    r = open("D:\\input.txt","r")
    strs =r.read()
    s = re.findall("\w+",strs)
    for i in s:
        m = re.search("\d+",i)
        n = re.search("\W+",i)
        if not m and  not n:
            values={'hl':'zh-CN','ie':'UTF-8','text':i,'langpair':"en|zh-CN" }
            url='http://translate.google.cn/translate_t'
            data = urllib.urlencode(values)
            req = urllib2.Request(url, data)
            req.add_header('User-Agent', "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")
            response = urllib2.urlopen(req)
            ul = URLLister()
            ul.feed(response.read())
            f.write(ul.result[0]+"\n")
    r.close()
    f.close()

     

  • Python正则表达式操作指南(转帖)

    2009-08-27 22:50:53

    原文作者:A.M. Kuchling (amk@amk.ca)
    授权许可:创作共用协议
    翻译人员:FireHare
    校对人员:Leal
    适用版本:Python 1.5 及后续版本

    简介

    Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。Python 1.5之前版本则是通过 regex 模块提供 Emecs 风格的模式。Emacs 风格模式可读性稍差些,而且功能也不强,因此编写新代码时尽量不要再使用 regex 模块,当然偶尔你还是可能在老代码里发现其踪影。

    就其本质而言,正则表达式(或 RE)是一种小型的、高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现。使用这个小型语言,你可以为想要匹配的相应字符串集指定规则;该字符串集可能包含英文语句、e-mail地址、TeX命令或任何你想搞定的东西。然后你可以问诸如“这个字符串匹配该模式吗?”或“在这个字符串中是否有部分匹配该模式呢?”。你也可以使用 RE 以各种方式来修改或分割字符串。

    正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。在高级用法中,也许还要仔细留意引擎是如何执行给定 RE ,如何以特定方式编写 RE 以令生产的字节码运行速度更快。本文并不涉及优化,因为那要求你已充分掌握了匹配引擎的内部机制。

    正则表达式语言相对小型和受限(功能有限),因此并非所有字符串处理都能用正则表达式完成。当然也有些任务可以用正则表达式完成,不过最终表达式会变得异常复杂。碰到这些情形时,编写 Python 代码进行处理可能反而更好;尽管 Python 代码比一个精巧的正则表达式要慢些,但它更易理解。

    简单模式

    我们将从最简单的正则表达式学习开始。由于正则表达式常用于字符串操作,那我们就从最常见的任务:字符匹配 下手。

    有关正则表达式底层的计算机科学上的详细解释(确定性和非确定性有限自动机),你可以查阅编写编译器相关的任何教科书。

    1. 字符匹配

    大多数字母和字符一般都会和自身匹配。例如,正则表达式 test 会和字符串“test”完全匹配。(你也可以使用大小写不敏感模式,它还能让这个 RE 匹配“Test”或“TEST”;稍后会有更多解释。)

    这个规则当然会有例外;有些字符比较特殊,它们和自身并不匹配,而是会表明应和一些特殊的东西匹配,或者它们会影响到 RE 其它部分的重复次数。本文很大篇幅专门讨论了各种元字符及其作用。

    这里有一个元字符的完整列表;其含义会在本指南余下部分进行讨论。

    . ^ $ * + ? { [ ] \ | ( )

    我们首先考察的元字符是 "[" 和 "]"。它们常用来指定一个字符类别,所谓字符类别就是你想匹配的一个字符集。字符可以单个列出,也可以用“-”号分隔的两个给定字符来表示一个字符区间。例如, [abc] 将匹配"a", "b", 或 "c"中的任意一个字符;也可以用区间[a-c]来表示同一字符集,和前者效果一致。如果你只想匹配小写字母,那么 RE 应写成 [a-z]。

    元字符在类别里并不起作用。例如,[akm$]将匹配字符"a", "k", "m", 或 "$" 中的任意一个;"$"通常用作元字符,但在字符类别里,其特性被除去,恢复成普通字符。

    你可以用补集来匹配不在区间范围内的字符。其做法是把"^"作为类别的首个字符;其它地方的"^"只会简单匹配 "^" 字符本身。例如,[^5] 将匹配除 "5" 之外的任意字符。

    也许最重要的元字符是反斜杠"\"。 做为 Python 中的字符串字母,反斜杠后面可以加不同的字符以表示不同特殊意义。它也可以用于取消所有的元字符,这样你就可以在模式中匹配它们了。举个例子,如果你需要匹配字符 "[" 或 "\",你可以在它们之前用反斜杠来取消它们的特殊意义: \[ 或 \\。

    一些用 "\" 开始的特殊字符所表示的预定义字符集通常是很有用的,象数字集,字母集,或其它非空字符集。下列是可用的预设特殊字符:

    \d

    * 匹配任何十进制数;它相当于类 [0-9]。

    \D

    * 匹配任何非数字字符;它相当于类 [^0-9]。

    \s

    * 匹配任何空白字符;它相当于类 [ \t\n\r\f\v]。

    \S

    * 匹配任何非空白字符;它相当于类 [^ \t\n\r\f\v]。

    \w

    * 匹配任何字母数字字符;它相当于类 [a-zA-Z0-9_]。

    \W

    * 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]。

    这样特殊字符都可以包含在一个字符类中。如,[\s,.]字符类将匹配任何空白字符或","或"."。

    本节最后一个元字符是 . 。它匹配除了换行字符外的任何字符,在 alternate 模式(re.DOTALL)下它甚至可以匹配换行。"." 通常被用于你想匹配“任何字符”的地方。

    2. 重复

    正则表达式第一件能做的事是能够匹配不定长的字符集,而这是其它能作用在字符串上的方法所不能做到的。 不过,如果那是正则表达式唯一的附加功能的话,那么它们也就不那么优秀了。它们的另一个功能就是你可以指定正则表达式的一部分的重复次数。

    我们讨论的第一个重复功能的元字符是 *。* 并不匹配字母字符 "*";相反,它指定前一个字符可以被匹配零次或更多次,而不是只有一次。

    举个例子,ca*t 将匹配 "ct" (0 个 "a" 字符), "cat" (1 个 "a"), "caaat" (3 个 "a" 字符)等等。RE 引擎有各种来自 C 的整数类型大小的内部限制,以防止它匹配超过2亿个 "a" 字符;你也许没有足够的内存去建造那么大的字符串,所以将不会累计到那个限制。

    象 * 这样地重复是“贪婪的”;当重复一个 RE 时,匹配引擎会试着重复尽可能多的次数。如果模式的后面部分没有被匹配,匹配引擎将退回并再次尝试更小的重复。

    一步步的示例可以使它更加清晰。让我们考虑表达式 a[bcd]*b。它匹配字母 "a",零个或更多个来自类 [bcd]中的字母,最后以 "b" 结尾。现在想一想该 RE 对字符串 "abcbd" 的匹配。

    Step      Matched        Explanation
    -------------------------------------
    1        a               匹配模式
    2        abcbd           引擎匹配 [bcd]*,并尽其所能匹配到字符串的结尾
    3        Failure         引擎尝试匹配 b,但当前位置已经是字符的最后了,所以失败
    4        abcb            退回,[bcd]*尝试少匹配一个字符。
    5        Failure         再次尝次b,但在当前最后一位字符是"d"。
    6        abc             再次退回,[bcd]*只匹配 "bc"。
    7        abcb            再次尝试 b ,这次当前位上的字符正好是 "b"

    RE 的结尾部分现在可以到达了,它匹配 "abcb"。这证明了匹配引擎一开始会尽其所能进行匹配,如果没有匹配然后就逐步退回并反复尝试 RE 剩下来的部分。直到它退回尝试匹配 [bcd] 到零次为止,如果随后还是失败,那么引擎就会认为该字符串根本无法匹配 RE 。

    另一个重复元字符是 +,表示匹配一或更多次。请注意 * 和 + 之间的不同;* 匹配零或更多次,所以根本就可以不出现,而 + 则要求至少出现一次。用同一个例子,ca+t 就可以匹配 "cat" (1 个 "a"), "caaat" (3 个 "a"), 但不能匹配 "ct"。

    还有更多的限定符。问号 ? 匹配一次或零次;你可以认为它用于标识某事物是可选的。例如:home-?brew 匹配 "homebrew" 或 "home-brew"。

    最复杂的重复限定符是 {m,n},其中 m 和 n 是十进制整数。该限定符的意思是至少有 m 个重复,至多到 n 个重复。举个例子,a/{1,3}b 将匹配 "a/b","a//b" 和 "a///b"。它不能匹配 "ab" 因为没有斜杠,也不能匹配 "a////b" ,因为有四个。

    你可以忽略 m 或 n;因为会为缺失的值假设一个合理的值。忽略 m 会认为下边界是 0,而忽略 n 的结果将是上边界为无穷大 -- 实际上是先前我们提到的 2 兆,但这也许同无穷大一样。

    细心的读者也许注意到其他三个限定符都可以用这样方式来表示。 {0,} 等同于 *,{1,} 等同于 +,而{0,1}则与 ? 相同。如果可以的话,最好使用 *,+,或?。很简单因为它们更短也再容易懂。

    使用正则表达式

    现在我们已经看了一些简单的正则表达式,那么我们实际在 Python 中是如何使用它们的呢? re 模块提供了一个正则表达式引擎的接口,可以让你将 REs 编译成对象并用它们来进行匹配。

    1. 编译正则表达式

    正则表达式被编译成 RegexObject 实例,可以为不同的操作提供方法,如模式匹配搜索或字符串替换。
    切换行号显示

    1 <<< import re
    2 <<< p = re.compile('ab*')
    3 <<< print p
    4 <re.RegexObject instance at 80b4150<

    re.compile() 也接受可选的标志参数,常用来实现不同的特殊功能和语法变更。我们稍后将查看所有可用的设置,但现在只举一个例子:
    切换行号显示

    1 <<< p = re.compile('ab*', re.IGNORECASE)

    RE 被做为一个字符串发送给 re.compile()。REs 被处理成字符串是因为正则表达式不是 Python 语言的核心部分,也没有为它创建特定的语法。(应用程序根本就不需要 REs,因此没必要包含它们去使语言说明变得臃肿不堪。)而 re 模块则只是以一个 C 扩展模块的形式来被 Python 包含,就象 socket 或 zlib 模块一样。

    将 REs 作为字符串以保证 Python 语言的简洁,但这样带来的一个麻烦就是象下节标题所讲的。

    2. 反斜杠的麻烦

    在早期规定中,正则表达式用反斜杠字符 ("\") 来表示特殊格式或允许使用特殊字符而不调用它的特殊用法。这就与 Python 在字符串中的那些起相同作用的相同字符产生了冲突。

    让我们举例说明,你想写一个 RE 以匹配字符串 "\section",可能是在一个 LATEX 文件查找。为了要在程序代码中判断,首先要写出想要匹配的字符串。接下来你需要在所有反斜杠和元字符前加反斜杠来取消其特殊意义。

    字符                  阶段
    --------------------------------------------
    \section       要匹配的字符串
    \\section      为 re.compile 取消反斜杠的特殊意义
    "\\\\section"  为字符串取消反斜杠

    简单地说,为了匹配一个反斜杠,不得不在 RE 字符串中写 '\\\\',因为正则表达式中必须是 "\\",而每个反斜杠按 Python 字符串字母表示的常规必须表示成 "\\"。在 REs 中反斜杠的这个重复特性会导致大量重复的反斜杠,而且所生成的字符串也很难懂。

    解决的办法就是为正则表达式使用 Python 的 raw 字符串表示;在字符串前加个 "r" 反斜杠就不会被任何特殊方式处理,所以 r"\n" 就是包含"\" 和 "n" 的两个字符,而 "\n" 则是一个字符,表示一个换行。正则表达式通常在 Python 代码中都是用这种 raw 字符串表示。

    常规字符串            Raw 字符串
    -------------------------------------------
    "ab*"                r"ab*"
    "\\\\section"        r"\\section"
    "\\w+\\s+\\1"        r"\w+\s+\1"

    3. 执行匹配

    一旦你有了已经编译了的正则表达式的对象,你要用它做什么呢?RegexObject 实例有一些方法和属性。这里只显示了最重要的几个,如果要看完整的列表请查阅 Library Refference。

    方法/属性         作用
    ------------------------------------------
    match()   决定 RE 是否在字符串刚开始的位置匹配
    search()  扫描字符串,找到这个 RE 匹配的位置
    findall() 找到 RE 匹配的所有子串,并把它们作为一个列表返回
    finditer() 找到 RE 匹配的所有子串,并把它们作为一个迭代器返回

    如果没有匹配到的话,match() 和 search() 将返回 None。如果成功的话,就会返回一个 MatchObject 实例,其中有这次匹配的信息:它是从哪里开始和结束,它所匹配的子串等等。

    你可以用采用人机对话并用 re 模块实验的方式来学习它。如果你有 Tkinter 的话,你也许可以考虑参考一下 Tools/scripts/redemo.py,一个包含在 Python 发行版里的示范程序。

    首先,运行 Python 解释器,导入 re 模块并编译一个 RE:
    切换行号显示

    1 Python 2.2.2 (#1, Feb 10 2003, 12:57:01)
    2 <<< import re
    3 <<< p = re.compile('[a-z]+')
    4 <<< p
    5 <_sre.SRE_Pattern object at 80c3c28<
    ERROR: EOF in multi-line statement

    现在,你可以试着用 RE 的 [a-z]+ 去匹配不同的字符串。一个空字符串将根本不能匹配,因为 + 的意思是 “一个或更多的重复次数”。在这种情况下 match() 将返回 None,因为它使解释器没有输出。你可以明确地打印出 match() 的结果来弄清这一点。
    切换行号显示

    1 <<< p.match("")
    2 <<< print p.match("")
    3 None

    现在,让我们试着用它来匹配一个字符串,如 "tempo"。这时,match() 将返回一个 MatchObject。因此你可以将结果保存在变量里以便后面使用。
    切换行号显示

    1 <<< m = p.match( 'tempo')
    2 <<< print m
    3 <_sre.SRE_Match object at 80c4f68<

    现在你可以查询 MatchObject 关于匹配字符串的相关信息了。MatchObject 实例也有几个方法和属性;最重要的那些如下所示:

    方法/属性            作用
    --------------------------------------
    group()    返回被 RE 匹配的字符串
    start()    返回匹配开始的位置
    end()      返回匹配结束的位置
    span()     返回一个元组包含匹配 (开始,结束) 的位置

    试试这些方法不久就会清楚它们的作用了:
    切换行号显示

    1 <<< m.group()
    2 'tempo'
    3 <<< m.start(), m.end()
    4 (0, 5)
    5 <<< m.span()
    6 (0, 5)

    group() 返回 RE 匹配的子串。start() 和 end() 返回匹配开始和结束时的索引。span() 则用单个元组把开始和结束时的索引一起返回。因为匹配方法检查到如果 RE 在字符串开始处开始匹配,那么 start() 将总是为零。然而, RegexObject 实例的 search 方法扫描下面的字符串的话,在这种情况下,匹配开始的位置就也许不是零了。
    切换行号显示

    1 <<< print p.match('::: message')
    2 None
    3 <<< m = p.search('::: message') ; print m
    4 <re.MatchObject instance at 80c9650<
    5 <<< m.group()
    6 'message'
    7 <<< m.span()
    8 (4, 11)

    在实际程序中,最常见的作法是将 MatchObject 保存在一个变量里,然后检查它是否为 None,通常如下所示:
    切换行号显示

    1 p = re.compile( ... )
    2 m = p.match( 'string goes here' )
    3 if m:
    4 print 'Match found: ', m.group()
    5 else:
    6 print 'No match'

    两个 RegexObject 方法返回所有匹配模式的子串。findall()返回一个匹配字符串列表:
    切换行号显示

    1 <<< p = re.compile('\d+')
    2 <<< p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
    3 ['12', '11', '10']

    findall() 在它返回结果时不得不创建一个列表。在 Python 2.2中,也可以用 finditer() 方法。
    切换行号显示

    1 <<< iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
    2 <<< iterator
    3 <callable-iterator object at 0x401833ac<
    4 <<< for match in iterator:
    5 ... print match.span()
    6 ...
    7 (0, 2)
    8 (22, 24)
    9 (29, 31)

    4. 模块级函数

    你不一定要产生一个 RegexObject 对象然后再调用它的方法;re 模块也提供了顶级函数调用如 match()、search()、sub() 等等。这些函数使用 RE 字符串作为第一个参数,而后面的参数则与相应 RegexObject 的方法参数相同,返回则要么是 None 要么就是一个 MatchObject 的实例。
    切换行号显示

    1 <<< print re.match(r'From\s+', 'Fromage amk')
    2 None
    3 <<< re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
    4 <re.MatchObject instance at 80c5978<

    Under the hood, 这些函数简单地产生一个 RegexOject 并在其上调用相应的方法。它们也在缓存里保存编译后的对象,因此在将来调用用到相同 RE 时就会更快。

    你将使用这些模块级函数,还是先得到一个 RegexObject 再调用它的方法呢?如何选择依赖于怎样用 RE 更有效率以及你个人编码风格。如果一个 RE 在代码中只做用一次的话,那么模块级函数也许更方便。如果程序包含很多的正则表达式,或在多处复用同一个的话,那么将全部定义放在一起,在一段代码中提前编译所有的 REs 更有用。从标准库中看一个例子,这是从 xmllib.py 文件中提取出来的:
    切换行号显示

    1 ref = re.compile( ... )
    2 entityref = re.compile( ... )
    3 charref = re.compile( ... )
    4 starttagopen = re.compile( ... )

    我通常更喜欢使用编译对象,甚至它只用一次,but few people will be as much of a purist about this as I am。

    5. 编译标志

    编译标志让你可以修改正则表达式的一些运行方式。在 re 模块中标志可以使用两个名字,一个是全名如 IGNORECASE,一个是缩写,一字母形式如 I。(如果你熟悉 Perl 的模式修改,一字母形式使用同样的字母;例如 re.VERBOSE的缩写形式是 re.X。)多个标志可以通过按位 OR-ing 它们来指定。如 re.I | re.M 被设置成 I 和 M 标志:

    这有个可用标志表,对每个标志后面都有详细的说明。

    标志               含义
    -----------------------------------------
    DOTALL, S        使 . 匹配包括换行在内的所有字符
    IGNORECASE, I    使匹配对大小写不敏感
    LOCALE, L        做本地化识别(locale-aware)匹配
    MULTILINE, M     多行匹配,影响 ^ 和 $
    VERBOSE, X       能够使用 REs 的 verbose 状态,使之被组织得更清晰易懂

    I
    IGNORECASE

    * 使匹配对大小写不敏感;字符类和字符串匹配字母时忽略大小写。举个例子,[A-Z]也可以匹配小写字母,Spam 可以匹配 "Spam", "spam", 或 "spAM"。这个小写字母并不考虑当前位置。

    L
    LOCALE

    * 影响 \w, \W, \b, 和 \B,这取决于当前的本地化设置。 locales 是 C 语言库中的一项功能,是用来为需要考虑不同语言的编程提供帮助的。举个例子,如果你正在处理法文文本,你想用 \w+ 来匹配文字,但 \w 只匹配字符类 [A-Za-z];它并不能匹配 "é" 或 "ç"。如果你的系统配置适当且本地化设置为法语,那么内部的 C 函数将告诉程序 "é" 也应该被认为是一个字母。当在编译正则表达式时使用 LOCALE 标志会得到用这些 C 函数来处理 \w 后的编译对象;这会更慢,但也会象你希望的那样可以用 \w+ 来匹配法文文本。

    M
    MULTILINE

    * (此时 ^ 和 $ 不会被解释; 它们将在 4.1 节被介绍.)

    使用 只匹配字符串的开始,而 $ 则只匹配字符串的结尾和直接在换行前(如果有的话)的字符串结尾。当本标志指定后, 匹配字符串的开始和字符串中每行的开始。同样的, $ 元字符匹配字符串结尾和字符串中每行的结尾(直接在每个换行之前)。

    S
    DOTALL

    * 使 "." 特殊字符完全匹配任何字符,包括换行;没有这个标志, "." 匹配除了换行外的任何字符。

    X
    VERBOSE

    * 该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。当该标志被指定时,在 RE 字符串中的空白符被忽略,除非该空白符在字符类中或在反斜杠之后;这可以让你更清晰地组织和缩进 RE。它也可以允许你将注释写入 RE,这些注释会被引擎忽略;注释用 "#"号 来标识,不过该符号不能在字符串或反斜杠之后。 举个例子,这里有一个使用 re.VERBOSE 的 RE;看看读它轻松了多少?
    切换行号显示

    1 charref = re.compile(r"""
    2 &[#] # Start of a numeric entity reference
    3 (
    4 [0-9]+[^0-9] # Decimal form
    5 | 0[0-7]+[^0-7] # Octal form
    6 | x[0-9a-fA-F]+[^0-9a-fA-F] # Hexadecimal form
    7 )
    8 """, re.VERBOSE)

    没有 verbose 设置, RE 会看起来象这样:
    切换行号显示

    1 charref = re.compile("&#([0-9]+[^0-9]"
    2 "|0[0-7]+[^0-7]"
    3 "|x[0-9a-fA-F]+[^0-9a-fA-F])")

    在上面的例子里,Python 的字符串自动连接可以用来将 RE 分成更小的部分,但它比用 re.VERBOSE 标志时更难懂。

    更多模式功能

    到目前为止,我们只展示了正则表达式的一部分功能。在本节,我们将展示一些新的元字符和如何使用组来检索被匹配的文本部分。

    1. 更多的元字符

    还有一些我们还没展示的元字符,其中的大部分将在本节展示。

    剩下来要讨论的一部分元字符是零宽界定符(zero-width assertions)。它们并不会使引擎在处理字符串时更快;相反,它们根本就没有对应任何字符,只是简单的成功或失败。举个例子, \b 是一个在单词边界定位当前位置的界定符(assertions),这个位置根本就不会被 \b 改变。这意味着零宽界定符(zero-width assertions)将永远不会被重复,因为如果它们在给定位置匹配一次,那么它们很明显可以被匹配无数次。

    |

    * 可选项,或者 "or" 操作符。如果 A 和 B 是正则表达式,A|B 将匹配任何匹配了 "A" 或 "B" 的字符串。| 的优先级非常低,是为了当你有多字符串要选择时能适当地运行。Crow|Servo 将匹配"Crow" 或 "Servo", 而不是 "Cro", 一个 "w" 或 一个 "S", 和 "ervo"。 为了匹配字母 "|",可以用 \|,或将其包含在字符类中,如[|]。

    ^

    * 匹配行首。除非设置 MULTILINE 标志,它只是匹配字符串的开始。在 MULTILINE 模式里,它也可以直接匹配字符串中的每个换行。 例如,如果你只希望匹配在行首单词 "From",那么 RE 将用 ^From。
    切换行号显示

    1 <<< print re.search('^From', 'From Here to Eternity')
    2 <re.MatchObject instance at 80c1520<
    3 <<< print re.search('^From', 'Reciting From Memory')
    4 None

    $

    * 匹配行尾,行尾被定义为要么是字符串尾,要么是一个换行字符后面的任何位置。
    切换行号显示

    1 <<< print re.search('}$', '{block}')
    2 <re.MatchObject instance at 80adfa8<
    3 <<< print re.search('}$', '{block} ')
    4 None
    5 <<< print re.search('}$', '{block}\n')
    6 <re.MatchObject instance at 80adfa8<

    匹配一个 "$",使用 \$ 或将其包含在字符类中,如[$]。

    \A

    *

    只匹配字符串首。当不在 MULTILINE 模式,\A 和 实际上是一样的。然而,在 MULTILINE 模式里它们是不同的;\A 只是匹配字符串首,而 还可以匹配在换行符之后字符串的任何位置。

    \Z

    *

    Matches only at the end of the string.
    只匹配字符串尾。

    \b

    * 单词边界。这是个零宽界定符(zero-width assertions)只用以匹配单词的词首和词尾。单词被定义为一个字母数字序列,因此词尾就是用空白符或非字母数字符来标示的。 下面的例子只匹配 "class" 整个单词;而当它被包含在其他单词中时不匹配。
    切换行号显示

    1 <<< p = re.compile(r'\bclass\b')
    2 <<< print p.search('no class at all')
    3 <re.MatchObject instance at 80c8f28<
    4 <<< print p.search('the declassified algorithm')
    5 None
    6 <<< print p.search('one subclass is')
    7 None

    当用这个特殊序列时你应该记住这里有两个微妙之处。第一个是 Python 字符串和正则表达式之间最糟的冲突。在 Python 字符串里,"\b" 是反斜杠字符,ASCII值是8。如果你没有使用 raw 字符串时,那么 Python 将会把 "\b" 转换成一个回退符,你的 RE 将无法象你希望的那样匹配它了。下面的例子看起来和我们前面的 RE 一样,但在 RE 字符串前少了一个 "r" 。
    切换行号显示

    1 <<< p = re.compile('\bclass\b')
    2 <<< print p.search('no class at all')
    3 None
    4 <<< print p.search('\b' + 'class' + '\b')
    5 <re.MatchObject instance at 80c3ee0<

    第二个在字符类中,这个限定符(assertion)不起作用,\b 表示回退符,以便与 Python 字符串兼容。

    \B

    * 另一个零宽界定符(zero-width assertions),它正好同 \b 相反,只在当前位置不在单词边界时匹配。

    2. 分组

    你经常需要得到比 RE 是否匹配还要多的信息。正则表达式常常用来分析字符串,编写一个 RE 匹配感兴趣的部分并将其分成几个小组。举个例子,一个 RFC-822 的头部用 ":" 隔成一个头部名和一个值,这就可以通过编写一个正则表达式匹配整个头部,用一组匹配头部名,另一组匹配头部值的方式来处理。

    组是通过 "(" 和 ")" 元字符来标识的。 "(" 和 ")" 有很多在数学表达式中相同的意思;它们一起把在它们里面的表达式组成一组。举个例子,你可以用重复限制符,象 *, +, ?, 和 {m,n},来重复组里的内容,比如说(ab)* 将匹配零或更多个重复的 "ab"。
    切换行号显示

    1 <<< p = re.compile('(ab)*')
    2 <<< print p.match('ababababab').span()
    3 (0, 10)

    组用 "(" 和 ")" 来指定,并且得到它们匹配文本的开始和结尾索引;这就可以通过一个参数用 group()、start()、end() 和 span() 来进行检索。组是从 0 开始计数的。组 0 总是存在;它就是整个 RE,所以 MatchObject 的方法都把组 0 作为它们缺省的参数。稍后我们将看到怎样表达不能得到它们所匹配文本的 span。
    切换行号显示

    1 <<< p = re.compile('(a)b')
    2 <<< m = p.match('ab')
    3 <<< m.group()
    4 'ab'
    5 <<< m.group(0)
    6 'ab'

    小组是从左向右计数的,从1开始。组可以被嵌套。计数的数值可以能过从左到右计算打开的括号数来确定。
    切换行号显示

    1 <<< p = re.compile('(a(b)c)d')
    2 <<< m = p.match('abcd')
    3 <<< m.group(0)
    4 'abcd'
    5 <<< m.group(1)
    6 'abc'
    7 <<< m.group(2)
    8 'b'

    group() 可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。
    切换行号显示

    1 <<< m.group(2,1,2)
    2 ('b', 'abc', 'b')

    The groups() 方法返回一个包含所有小组字符串的元组,从 1 到 所含的小组号。
    切换行号显示

    1 <<< m.groups()
    2 ('abc', 'b')

    模式中的逆向引用允许你指定先前捕获组的内容,该组也必须在字符串当前位置被找到。举个例子,如果组 1 的内容能够在当前位置找到的话,\1 就成功否则失败。记住 Python 字符串也是用反斜杠加数据来允许字符串中包含任意字符的,所以当在 RE 中使用逆向引用时确保使用 raw 字符串。

    例如,下面的 RE 在一个字符串中找到成双的词。
    切换行号显示

    1 <<< p = re.compile(r'(\b\w+)\s+\1')
    2 <<< p.search('Paris in the the spring').group()
    3 'the the'

    象这样只是搜索一个字符串的逆向引用并不常见 -- 用这种方式重复数据的文本格式并不多见 -- 但你不久就可以发现它们用在字符串替换上非常有用。

    3. 无捕获组和命名组

    精心设计的 REs 也许会用很多组,既可以捕获感兴趣的子串,又可以分组和结构化 RE 本身。在复杂的 REs 里,追踪组号变得困难。有两个功能可以对这个问题有所帮助。它们也都使用正则表达式扩展的通用语法,因此我们来看看第一个。

    Perl 5 对标准正则表达式增加了几个附加功能,Python 的 re 模块也支持其中的大部分。选择一个新的单按键元字符或一个以 "\" 开始的特殊序列来表示新的功能,而又不会使 Perl 正则表达式与标准正则表达式产生混乱是有难度的。如果你选择 "&" 做为新的元字符,举个例子,老的表达式认为 "&" 是一个正常的字符,而不会在使用 \& 或 [&] 时也不会转义。

    Perl 开发人员的解决方法是使用 (?...) 来做为扩展语法。"?" 在括号后面会直接导致一个语法错误,因为 "?" 没有任何字符可以重复,因此它不会产生任何兼容问题。紧随 "?" 之后的字符指出扩展的用途,因此 (?=foo)

    Python 新增了一个扩展语法到 Perl 扩展语法中。如果在问号后的第一个字符是 "P",你就可以知道它是针对 Python 的扩展。目前有两个这样的扩展: (?P<name<...) 定义一个命名组,(?P=name) 则是对命名组的逆向引用。如果 Perl 5 的未来版本使用不同的语法增加了相同的功能,那么 re 模块也将改变以支持新的语法,这是为了兼容性的目的而保持的 Python 专用语法。

    现在我们看一下普通的扩展语法,我们回过头来简化在复杂 REs 中使用组运行的特性。因为组是从左到右编号的,而且一个复杂的表达式也许会使用许多组,它可以使跟踪当前组号变得困难,而修改如此复杂的 RE 是十分麻烦的。在开始时插入一个新组,你可以改变它之后的每个组号。

    首先,有时你想用一个组去收集正则表达式的一部分,但又对组的内容不感兴趣。你可以用一个无捕获组: (?:...) 来实现这项功能,这样你可以在括号中发送任何其他正则表达式。
    切换行号显示

    1 <<< m = re.match("([abc])+", "abc")
    2 <<< m.groups()
    3 ('c',)
    4 <<< m = re.match("(?:[abc])+", "abc")
    5 <<< m.groups()
    6 ()

    除了捕获匹配组的内容之外,无捕获组与捕获组表现完全一样;你可以在其中放置任何字符,可以用重复元字符如 "*" 来重复它,可以在其他组(无捕获组与捕获组)中嵌套它。(?:...) 对于修改已有组尤其有用,因为你可以不用改变所有其他组号的情况下添加一个新组。捕获组和无捕获组在搜索效率方面也没什么不同,没有哪一个比另一个更快。

    其次,更重要和强大的是命名组;与用数字指定组不同的是,它可以用名字来指定。

    命令组的语法是 Python 专用扩展之一: (?P<name<...)。名字很明显是组的名字。除了该组有个名字之外,命名组也同捕获组是相同的。MatchObject 的方法处理捕获组时接受的要么是表示组号的整数,要么是包含组名的字符串。命名组也可以是数字,所以你可以通过两种方式来得到一个组的信息:
    切换行号显示

    1 <<< p = re.compile(r'(?P<word<\b\w+\b)')
    2 <<< m = p.search( '(((( Lots of punctuation )))' )
    3 <<< m.group('word')
    4 'Lots'
    5 <<< m.group(1)
    6 'Lots'

    命名组是便于使用的,因为它可以让你使用容易记住的名字来代替不得不记住的数字。这里有一个来自 imaplib 模块的 RE 示例:
    切换行号显示

    1 InternalDate = re.compile(r'INTERNALDATE "'
    2 r'(?P<day<[ 123][0-9])-(?P<mon<[A-Z][a-z][a-z])-'
    3 r'(?P<year<[0-9][0-9][0-9][0-9])'
    4 r' (?P<hour<[0-9][0-9]):(?P<min<[0-9][0-9]):(?P<sec<[0-9][0-9])'
    5 r' (?P<zonen<[-+])(?P<zoneh<[0-9][0-9])(?P<zonem<[0-9][0-9])'
    6 r'"')

    很明显,得到 m.group('zonem') 要比记住得到组 9 要容易得多。

    因为逆向引用的语法,象 (...)\1 这样的表达式所表示的是组号,这时用组名代替组号自然会有差别。还有一个 Python 扩展:(?P=name) ,它可以使叫 name 的组内容再次在当前位置发现。正则表达式为了找到重复的单词,(\b\w+)\s+\1 也可以被写成 (?P<word<\b\w+)\s+(?P=word):
    切换行号显示

    1 <<< p = re.compile(r'(?P<word<\b\w+)\s+(?P=word)')
    2 <<< p.search('Paris in the the spring').group()
    3 'the the'

    4. 前向界定符

    另一个零宽界定符(zero-width assertion)是前向界定符。前向界定符包括前向肯定界定符和后向肯定界定符,所下所示:

    (?=...)

    * 前向肯定界定符。如果所含正则表达式,以 ... 表示,在当前位置成功匹配时成功,否则失败。但一旦所含表达式已经尝试,匹配引擎根本没有提高;模式的剩余部分还要尝试界定符的右边。

    (?!...)

    * 前向否定界定符。与肯定界定符相反;当所含表达式不能在字符串当前位置匹配时成功

    通过示范在哪前向可以成功有助于具体实现。考虑一个简单的模式用于匹配一个文件名,并将其通过 "." 分成基本名和扩展名两部分。如在 "news.rc" 中,"news" 是基本名,"rc" 是文件的扩展名。

    匹配模式非常简单:

    .*[.].*$

    注意 "." 需要特殊对待,因为它是一个元字符;我把它放在一个字符类中。另外注意后面的 $; 添加这个是为了确保字符串所有的剩余部分必须被包含在扩展名中。这个正则表达式匹配 "foo.bar"、"autoexec.bat"、 "sendmail.cf" 和 "printers.conf"。

    现在,考虑把问题变得复杂点;如果你想匹配的扩展名不是 "bat" 的文件名?一些不正确的尝试:

    .*[.][^b].*$

    上面的第一次去除 "bat" 的尝试是要求扩展名的第一个字符不是 "b"。这是错误的,因为该模式也不能匹配 "foo.bar"。

    .*[.]([^b]..|.[^a].|..[^t])$

    当你试着修补第一个解决方法而要求匹配下列情况之一时表达式更乱了:扩展名的第一个字符不是 "b"; 第二个字符不是 "a";或第三个字符不是 "t"。这样可以接受 "foo.bar" 而拒绝 "autoexec.bat",但这要求只能是三个字符的扩展名而不接受两个字符的扩展名如 "sendmail.cf"。我们将在努力修补它时再次把该模式变得复杂。

    .*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$

    在第三次尝试中,第二和第三个字母都变成可选,为的是允许匹配比三个字符更短的扩展名,如 "sendmail.cf"。

    该模式现在变得非常复杂,这使它很难读懂。更糟的是,如果问题变化了,你想扩展名不是 "bat" 和 "exe",该模式甚至会变得更复杂和混乱。

    前向否定把所有这些裁剪成:

    .*[.](?!bat$).*$

    前向的意思:如果表达式 bat 在这里没有匹配,尝试模式的其余部分;如果 bat$ 匹配,整个模式将失败。后面的 $ 被要求是为了确保象 "sample.batch" 这样扩展名以 "bat" 开头的会被允许。

    将另一个文件扩展名排除在外现在也容易;简单地将其做为可选项放在界定符中。下面的这个模式将以 "bat" 或 "exe" 结尾的文件名排除在外。

    .*[.](?!bat$|exe$).*$

    修改字符串

    到目前为止,我们简单地搜索了一个静态字符串。正则表达式通常也用不同的方式,通过下面的 RegexObject 方法,来修改字符串。

    方法/属性        作用
    ------------------------------------
    split()       将字符串在 RE 匹配的地方分片并生成一个列表,
    sub()         找到 RE 匹配的所有子串,并将其用一个不同的字符串替换
    subn()        与 sub() 相同,但返回新的字符串和替换次数

    1. 将字符串分片

    RegexObject 的 split() 方法在 RE 匹配的地方将字符串分片,将返回列表。它同字符串的 split() 方法相似但提供更多的定界符;split()只支持空白符和固定字符串。就象你预料的那样,也有一个模块级的 re.split() 函数。

    split(string [, maxsplit = 0])

    * 通过正则表达式将字符串分片。如果捕获括号在 RE 中使用,那么它们的内容也会作为结果列表的一部分返回。如果 maxsplit 非零,那么最多只能分出 maxsplit 个分片。

    你可以通过设置 maxsplit 值来限制分片数。当 maxsplit 非零时,最多只能有 maxsplit 个分片,字符串的其余部分被做为列表的最后部分返回。在下面的例子中,定界符可以是非数字字母字符的任意序列。
    切换行号显示

    1 <<< p = re.compile(r'\W+')
    2 <<< p.split('This is a test, short and sweet, of split().')
    3 ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
    4 <<< p.split('This is a test, short and sweet, of split().', 3)
    5 ['This', 'is', 'a', 'test, short and sweet, of split().']

    有时,你不仅对定界符之间的文本感兴趣,也需要知道定界符是什么。如果捕获括号在 RE 中使用,那么它们的值也会当作列表的一部分返回。比较下面的调用:
    切换行号显示

    1 <<< p = re.compile(r'\W+')
    2 <<< p2 = re.compile(r'(\W+)')
    3 <<< p.split('This... is a test.')
    4 ['This', 'is', 'a', 'test', '']
    5 <<< p2.split('This... is a test.')
    6 ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']

    模块级函数 re.split() 将 RE 作为第一个参数,其他一样。
    切换行号显示

    1 <<< re.split('[\W]+', 'Words, words, words.')
    2 ['Words', 'words', 'words', '']
    3 <<< re.split('([\W]+)', 'Words, words, words.')
    4 ['Words', ', ', 'words', ', ', 'words', '.', '']
    5 <<< re.split('[\W]+', 'Words, words, words.', 1)
    6 ['Words', 'words, words.']

    2. 搜索和替换

    其他常见的用途就是找到所有模式匹配的字符串并用不同的字符串来替换它们。sub() 方法提供一个替换值,可以是字符串或一个函数,和一个要被处理的字符串。

    sub(replacement, string[, count = 0])

    * 返回的字符串是在字符串中用 RE 最左边不重复的匹配来替换。如果模式没有发现,字符将被没有改变地返回。 可选参数 count 是模式匹配后替换的最大次数;count 必须是非负整数。缺省值是 0 表示替换所有的匹配。

    这里有个使用 sub() 方法的简单例子。它用单词 "colour" 替换颜色名。
    切换行号显示

    1 <<< p = re.compile( '(blue|white|red)')
    2 <<< p.sub( 'colour', 'blue socks and red shoes')
    3 'colour socks and colour shoes'
    4 <<< p.sub( 'colour', 'blue socks and red shoes', count=1)
    5 'colour socks and red shoes'

    subn() 方法作用一样,但返回的是包含新字符串和替换执行次数的两元组。
    切换行号显示

    1 <<< p = re.compile( '(blue|white|red)')
    2 <<< p.subn( 'colour', 'blue socks and red shoes')
    3 ('colour socks and colour shoes', 2)
    4 <<< p.subn( 'colour', 'no colours at all')
    5 ('no colours at all', 0)

    空匹配只有在它们没有紧挨着前一个匹配时才会被替换掉。
    切换行号显示

    1 <<< p = re.compile('x*')
    2 <<< p.sub('-', 'abxd')
    3 '-a-b-d-'

    如果替换的是一个字符串,任何在其中的反斜杠都会被处理。"\n" 将会被转换成一个换行符,"\r"转换成回车等等。未知的转义如 "\j" 是 left alone。逆向引用,如 "\6",被 RE 中相应的组匹配而被子串替换。这使你可以在替换后的字符串中插入原始文本的一部分。

    这个例子匹配被 "{" 和 "}" 括起来的单词 "section",并将 "section" 替换成 "subsection"。
    切换行号显示

    1 <<< p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
    2 <<< p.sub(r'subsection{\1}','section{First} section{second}')
    3 'subsection{First} subsection{second}'

    还可以指定用 (?P<name<...) 语法定义的命名组。"\g<name<" 将通过组名 "name" 用子串来匹配,并且 "\g<number<" 使用相应的组号。所以 "\g<2<" 等于 "\2",但能在替换字符串里含义不清,如 "\g<2<0"。("\20" 被解释成对组 20 的引用,而不是对后面跟着一个字母 "0" 的组 2 的引用。)
    切换行号显示

    1 <<< p = re.compile('section{ (?P<name< [^}]* ) }', re.VERBOSE)
    2 <<< p.sub(r'subsection{\1}','section{First}')
    3 'subsection{First}'
    4 <<< p.sub(r'subsection{\g<1<}','section{First}')
    5 'subsection{First}'
    6 <<< p.sub(r'subsection{\g<name<}','section{First}')
    7 'subsection{First}'

    替换也可以是一个甚至给你更多控制的函数。如果替换是个函数,该函数将会被模式中每一个不重复的匹配所调用。在每个调用时,函数被作为 MatchObject 的匹配函属,并可以使用这个信息去计算预期的字符串并返回它。

    在下面的例子里,替换函数将十进制翻译成十六进制:
    切换行号显示

    1 <<< def hexrepl( match ):
    2 ... "Return the hex string for a decimal number"
    3 ... value = int( match.group() )
    4 ... return hex(value)
    5 ...
    6 <<< p = re.compile(r'\d+')
    7 <<< p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
    8 'Call 0xffd2 for printing, 0xc000 for user code.'

    当使用模块级的 re.sub() 函数时,模式作为第一个参数。模式也许是一个字符串或一个 RegexObject;如果你需要指定正则表达式标志,你必须要么使用 RegexObject 做第一个参数,或用使用模式内嵌修正器,如 sub("(?i)b+", "x", "bbbb BBBB") returns 'x x'。

    常见问题

    正则表达式对一些应用程序来说是一个强大的工具,但在有些时候它并不直观而且有时它们不按你期望的运行。本节将指出一些最容易犯的常见错误。

    1. 使用字符串方式

    有时使用 re 模块是个错误。如果你匹配一个固定的字符串或单个的字符类,并且你没有使用 re 的任何象 IGNORECASE 标志的功能,那么就没有必要使用正则表达式了。字符串有一些方法是对固定字符串进行操作的,它们通常快很多,因为都是一个个经过优化的C 小循环,用以代替大的、更具通用性的正则表达式引擎。

    举个用一个固定字符串替换另一个的例子;如,你可以把 "deed" 替换成 "word"。re.sub() seems like the function to use for this, but consider the replace() method. 注意 replace() 也可以在单词里面进行替换,可以把 "swordfish" 变成 "sdeedfish",不过 RE 也是可以做到的。(为了避免替换单词的一部分,模式将写成 \bword\b,这是为了要求 "word" 两边有一个单词边界。这是个超出替换能力的工作)。

    另一个常见任务是从一个字符串中删除单个字符或用另一个字符来替代它。你也许可以用象 re.sub('\n',' ',S) 这样来实现,但 translate() 能够实现这两个任务,而且比任何正则表达式操作起来更快。

    总之,在使用 re 模块之前,先考虑一下你的问题是否可以用更快、更简单的字符串方法来解决。

    2. match() vs search()

    match() 函数只检查 RE 是否在字符串开始处匹配,而 search() 则是扫描整个字符串。记住这一区别是重要的。记住,match() 只报告一次成功的匹配,它将从 0 处开始;如果匹配不是从 0 开始的,match() 将不会报告它。
    切换行号显示

    1 <<< print re.match('super', 'superstition').span()
    2 (0, 5)
    3 <<< print re.match('super', 'insuperable')
    4 None

    另一方面,search() 将扫描整个字符串,并报告它找到的第一个匹配。
    切换行号显示

    1 <<< print re.search('super', 'superstition').span()
    2 (0, 5)
    3 <<< print re.search('super', 'insuperable').span()
    4 (2, 7)

    有时你可能倾向于使用 re.match(),只在RE的前面部分添加 .* 。请尽量不要这么做,最好采用 re.search() 代替之。正则表达式编译器会对 REs 做一些分析以便可以在查找匹配时提高处理速度。一个那样的分析机会指出匹配的第一个字符是什么;举个例子,模式 Crow 必须从 "C" 开始匹配。分析机可以让引擎快速扫描字符串以找到开始字符,并只在 "C" 被发现后才开始全部匹配。

    添加 .* 会使这个优化失败,这就要扫描到字符串尾部,然后回溯以找到 RE 剩余部分的匹配。使用 re.search() 代替。

    3. 贪婪 vs 不贪婪

    当重复一个正则表达式时,如用 a*,操作结果是尽可能多地匹配模式。当你试着匹配一对对称的定界符,如 HTML 标志中的尖括号时这个事实经常困扰你。匹配单个 HTML 标志的模式不能正常工作,因为 .* 的本质是“贪婪”的
    切换行号显示

    1 <<< s = '<html<<head<<title<Title</title<'
    2 <<< len(s)
    3 32
    4 <<< print re.match('<.*<', s).span()
    5 (0, 32)
    6 <<< print re.match('<.*<', s).group()
    7 <html<<head<<title<Title</title<

    RE 匹配 在 "<html<" 中的 "<",.* 消耗掉子符串的剩余部分。在 RE 中保持更多的左,虽然 < 不能匹配在字符串结尾,因此正则表达式必须一个字符一个字符地回溯,直到它找到 < 的匹配。最终的匹配从 "<html" 中的 "<" 到 "</title<" 中的 "<",这并不是你所想要的结果。

    在这种情况下,解决方案是使用不贪婪的限定符 *?、+?、?? 或 {m,n}?,尽可能匹配小的文本。在上面的例子里, "<" 在第一个 "<" 之后被立即尝试,当它失败时,引擎一次增加一个字符,并在每步重试 "<"。这个处理将得到正确的结果:
    切换行号显示

    1 <<< print re.match('<.*?<', s).group()
    2 <html<

    (注意用正则表达式分析 HTML 或 XML 是痛苦的。变化混乱的模式将处理常见情况,但 HTML 和 XML 则是明显会打破正则表达式的特殊情况;当你编写一个正则表达式去处理所有可能的情况时,模式将变得非常复杂。象这样的任务用 HTML 或 XML 解析器。

    4. 不用 re.VERBOSE

    现在你可能注意到正则表达式的表示是十分紧凑,但它们非常不好读。中度复杂的 REs 可以变成反斜杠、圆括号和元字符的长长集合,以致于使它们很难读懂。

    在这些 REs 中,当编译正则表达式时指定 re.VERBOSE 标志是有帮助的,因为它允许你可以编辑正则表达式的格式使之更清楚。

    re.VERBOSE 标志有这么几个作用。在正则表达式中不在字符类中的空白符被忽略。这就意味着象 dog | cat 这样的表达式和可读性差的 dog|cat 相同,但 [a b] 将匹配字符 "a"、"b" 或 空格。另外,你也可以把注释放到 RE 中;注释是从 "#" 到下一行。当使用三引号字符串时,可以使 REs 格式更加干净:
    切换行号显示

    1 pat = re.compile(r"""
    2 \s* # Skip leading whitespace
    3 (?P<header<[^:]+) # Header name
    4 \s* : # Whitespace, and a colon
    5 (?P<value<.*?) # The header's value -- *? used to
    6 # lose the following trailing whitespace
    7 \s*$ # Trailing whitespace to end-of-line
    8 """, re.VERBOSE)

    这个要难读得多:
    切换行号显示

    1 pat = re.compile(r"\s*(?P<header<[^:]+)\s*:(?P<value<.*?)\s*$")

    反馈

    正则表达式是一个复杂的主题。本文能否有助于你理解呢?那些部分是否不清晰,或在这儿没有找到你所遇到的问题?如果是那样的话,请将建议发给作者以便改进。

    描述正则表达式最全面的书非Jeffrey Friedl 写的《精通正则表达式》莫属,该书由O'Reilly 出版。可惜该书只专注于 Perl 和 Java 风格的正则表达式,不含任何 Python 材料,所以不足以用作Python编程时的参考。(第一版包含有 Python 现已过时的 regex 模块,自然用处不大)。

  • 学习Python的轨迹(转帖)

    2009-08-27 22:35:54

    根据学习经验,总结了以下十点和大家分享:
    1)学好python的第一步,就是马上到
    www.python.org网站上下载一个python版本。我建议初学者,不要下载具有IDE功能的集成开发环境,比如Eclipse插件等。
    2)下载完毕后,就可以开始学习了。学习过程中,我建议可以下载一些python的学习文档,比如《dive into python》,《OReilly - Learning Python》等等。通过学习语法,掌握python中的关键字语法,函数语法,数学表达式等等
    3)学完了基本语法后,就可以进行互动式学习了。python具备很好的交互学习模式,对于书本上的例子我们可以通过交互平台进行操练,通过练习加深印象,达到学习掌握的目的。
    4)通过以上三个步骤的学习后,我们大致掌握了python的常用方法、关键字用法以及函数语法等。接下去的学习上,我们就可以着手学习常用模块的使用, 比如os,os.path,sys,string模块等。我们可以在交互环境中先熟悉使用其中的函数,如果遇到函数的使用上的问题,可以参考python 安装后的自带chm帮助文件。
    5)为了更好得掌握python,我们的学习不能只是停留在学习一些语法或者api阶段。在此阶段中,我们可以尝试用python解决我们项目中遇到的一 些问题,如果项目不是用python开发的,那我们可以想想能不能用python制作一些项目组可以使用的一些工具(utility),通过这些工具简化 项目组成员的任务,提高我们的工作效率。如果没有项目,我们也可以自己找些题目来自己练习练习。
    6)经过以上锻炼后,我们的python知识水平肯定是越来越高。接下去的学习,我们就要更上一层楼。为了学以致用,真正能应用于项目开发或产品开发,我 们还必须学习企业应用开发中必须要掌握的网络和数据库知识。在此的学习就不光是python语言本身的学习了,如果之前没有学习和掌握很网络和数据库知 识,在此阶段我们可以借此机会补习一把。
    7)在此,我想我们对python的使用以及信手拈来了,即使忘了api的用法,我们也可以在短时间内通过查看文档来使用api。那么接下去,我们要学习什么呢?那就是设计能力,在学习设计能力的过程中,如果对类等面向对象的概念不清楚的,在此阶段也可以学习或加以巩固。就像飞机设计师设计飞机通过学习模型来设计一样,我们也可以通过学习书上的经典例子来学习设计。等有了设计的基本概念后,我们就可以着手设计我们的程序了。在此阶段中,我们重要的是学习抽象的思想,通过隔离变化点来设计我们的模块。
    8)到此阶段,我们已经是真正入门了。在接下去的工作中,就是要快速地通过我们的所学来服务项目了。在此阶段,我们除了掌握python自带的模块外,我 们最好在掌握一些业界广泛使用的开源框架,比如twisted、peak、django、xml等。通过熟练使用它们,达到闪电开发,大大节省项目宝贵时 间。
    9)你已经是个python行家了,在此阶段,我们在工作中会遇到一些深层次的、具体的困难问题。面对这些问题,我们已经有自己的思考方向和思路了。我们 时常会上网观看python的最新发展动态,最新python技术和开源项目,我们可以参与python论坛并结交社区中一些python道友。
    10)你已经是个python专家,在此阶段你应该是个python技术传播者。时不时在组织中开坛讲座,并在博客上传播你的python见解。你会上论 坛帮助同行们解决他们提出的问题,你会给
    www.python.org网站提出你的宝贵建议,并为python语言发展献计献策。
    任何知识的学习无止境,python的学习也不另外。在掌握python的用法、api和框架后,我们更要学习设计模式、开发方法论等
  • LinkedIn的悲哀

    2009-04-13 01:58:29

      注册linkedin也好几天了,目前的connections依然为0.唉,突然有些凄凉的感觉,自己的交际圈真是窄的可怜啊.看着别人几百的connections,真是眼红啊.要努力了.
  • 罪过,罪过!

    2009-04-13 01:53:28

      今天周末出去逛街,看到路旁有卖小金鱼的,见猎心喜就买了几条,不成想回到家后不久就死了几条.罪过啊,希望金鱼的在天之灵可以宽恕我的无心之失.
  • 在记录集中插入记录

    2009-04-04 13:14:50

    '在记录集中插入记录

    '建立连接对象
    Set bjconn = CreateObject("adodb.connection")

    '建立记录集对象
    Set bjrecordset =CreateObject("adodb.recordset")

    objconn.Open _
    "Provider = SQLOLEDB;Data Source=.;Trusted_Connection =yes;"&_
    "Initial Catalog =Cwxt;User Id =sa;password=1;"
    objrecordset.Open "select * from tbl_user",objconn,3,3

    objrecordset.AddNew()
    objrecordset.Fields(0).Value ="1"
    objrecordset.Fields(1).Value ="22"
    objrecordset.Fields(2).Value ="33"
    objrecordset.Update()

    objconn.Close
    objrecordset.Close

  • 复制Excel某列数据到文本文件中

    2009-04-01 00:51:24

     

    Set bjexcel = CreateObject("excel.application")
    objexcel.Visible = True
    Set bjwork = objexcel.Workbooks.Open("d:\1.xls")
    Set bjsheet = objwork.worksheets(1)
    '行
    i=1
    '列
    n=3
    Do While True
        strValue = objsheet.Cells(i,n)
        If strValue = "" Then
            Exit Do
        End If
        strText = strText & strValue & vbCrLf
        i = i + 1
    Loop

    objExcel.Quit

    Set bjFSO = CreateObject("Scripting.FileSystemObject")
    Set bjFile = objFSO.CreateTextFile("d:\ExcelData.txt")

    objFile.Write strText
    objFile.Close

  • Software QA and testing FAQ

    2008-09-12 02:58:05

    What is 'Software Quality Assurance'? Software QA involves the entire software development PROCESS - monitoring and improving the process, making sure that any agreed-upon standards and procedures are followed, and ensuring that problems are found and dealt with. It is oriented to 'prevention'. (See the Bookstore section's 'Software QA' category for a list of useful books on Software Quality Assurance.) 

    Return to top of this page's FAQ list 

    What is 'Software Testing'? 
    Testing involves operation of a system or application under controlled conditions and evaluating the results (eg, 'if the user is in interface A of the application while using hardware B, and does C, then D should happen'). The controlled conditions should include both normal and abnormal conditions. Testing should intentionally attempt to make things go wrong to determine if things happen when they shouldn't or things don't happen when they should. It is oriented to 'detection'. (See the Bookstore section's 'Software Testing' category for a list of useful books on Software Testing.) 
    Organizations vary considerably in how they assign responsibility for QA and testing. Sometimes they're the combined responsibility of one group or individual. Also common are project teams that include a mix of testers and developers who work closely together, with overall QA processes monitored by project managers. It will depend on what best fits an organization's size and business structure. 

    Return to top of this page's FAQ list 

    What are some recent major computer system failures caused by software bugs? 
    Software problems in the automated baggage sorting system of a major airport in February 2008 prevented thousands of passengers from checking baggage for their flights. It was reported that the breakdown occurred during a software upgrade, despite pre-testing of the software. The system continued to have problems in subsequent months. 
    News reports in December of 2007 indicated that significant software problems were continuing to occur in a new ERP payroll system for a large urban school system. It was believed that more than one third of employees had received incorrect paychecks at various times since the new system went live the preceding January, resulting in overpayments of $53 million, as well as underpayments. An employees' union brought a lawsuit against the school system, the cost of the ERP system was expected to rise by 40%, and the non-payroll part of the ERP system was delayed. Inadequate testing reportedly contributed to the problems. 
    In November of 2007 a regional government reportedly brought a multi-million dollar lawsuit against a software services vendor, claiming that the vendor 'minimized quality' in delivering software for a large criminal justice information system and the system did not meet requirements. The vendor also sued its subcontractor on the project. 
    In June of 2007 news reports claimed that software flaws in a popular online stock-picking contest could be used to gain an unfair advantage in pursuit of the game's large cash prizes. Outside investigators were called in and in July the contest winner was announced. Reportedly the winner had previously been in 6th place, indicating that the top 5 contestants may have been disqualified. 
    A software problem contributed to a rail car fire in a major underground metro system in April of 2007 according to newspaper accounts. The software reportedly failed to perform as expected in detecting and preventing excess power usage in equipment on a new passenger rail car, resulting in overheating and fire in the rail car, and evacuation and shutdown of part of the system. 
    Tens of thousands of medical devices were recalled in March of 2007 to correct a software bug. According to news reports, the software would not reliably indicate when available power to the device was too low. 
    A September 2006 news report indicated problems with software utilized in a state government's primary election, resulting in periodic unexpected rebooting of voter checkin machines, which were separate from the electronic voting machines, and resulted in confusion and delays at voting sites. The problem was reportedly due to insufficient testing. 
    In August of 2006 a U.S. government student loan service erroneously made public the personal data of as many as 21,000 borrowers on it's web site, due to a software error. The bug was fixed and the government department subsequently offered to arrange for free credit monitoring services for those affected. 
    A software error reportedly resulted in overbilling of up to several thousand dollars to each of 11,000 customers of a major telecommunications company in June of 2006. It was reported that the software bug was fixed within days, but that correcting the billing errors would take much longer. 
    News reports in May of 2006 described a multi-million dollar lawsuit settlement paid by a healthcare software vendor to one of its customers. It was reported that the customer claimed there were problems with the software they had contracted for, including poor integration of software modules, and problems that resulted in missing or incorrect data used by medical personnel. 
    In early 2006 problems in a government's financial monitoring software resulted in incorrect election candidate financial reports being made available to the public. The government's election finance reporting web site had to be shut down until the software was repaired. 
    Trading on a major Asian stock exchange was brought to a halt in November of 2005, reportedly due to an error in a system software upgrade. The problem was rectified and trading resumed later the same day. 
    A May 2005 newspaper article reported that a major hybrid car manufacturer had to install a software fix on 20,000 vehicles due to problems with invalid engine warning lights and occasional stalling. In the article, an automotive software specialist indicated that the automobile industry spends $2 billion to $3 billion per year fixing software problems. 
    Media reports in January of 2005 detailed severe problems with a $170 million high-profile U.S. government IT systems project. Software testing was one of the five major problem areas according to a report of the commission reviewing the project. In March of 2005 it was decided to scrap the entire project. 
    In July 2004 newspapers reported that a new government welfare management system in Canada costing several hundred million dollars was unable to handle a simple benefits rate increase after being put into live operation. Reportedly the original contract allowed for only 6 weeks of acceptance testing and the system was never tested for its ability to handle a rate increase. 
    Millions of bank accounts were impacted by errors due to installation of inadequately tested software code in the transaction processing system of a major North American bank, according to mid-2004 news reports. Articles about the incident stated that it took two weeks to fix all the resulting errors, that additional problems resulted when the incident drew a large number of e-mail phishing attacks against the bank's customers, and that the total cost of the incident could exceed $100 million. 
    A bug in site management software utilized by companies with a significant percentage of worldwide web traffic was reported in May of 2004. The bug resulted in performance problems for many of the sites simultaneously and required disabling of the software until the bug was fixed. 
    According to news reports in April of 2004, a software bug was determined to be a major contributor to the 2003 Northeast blackout, the worst power system failure in North American history. The failure involved loss of electrical power to 50 million customers, forced shutdown of 100 power plants, and economic losses estimated at $6 billion. The bug was reportedly in one utility company's vendor-supplied power monitoring and management system, which was unable to correctly handle and report on an unusual confluence of initially localized events. The error was found and corrected after examining millions of lines of code. 
    In early 2004, news reports revealed the intentional use of a software bug as a counter-espionage tool. According to the report, in the early 1980's one nation surreptitiously allowed a hostile nation's espionage service to steal a version of sophisticated industrial software that had intentionally-added flaws. This eventually resulted in major industrial disruption in the country that used the stolen flawed software. 
    A major U.S. retailer was reportedly hit with a large government fine in October of 2003 due to web site errors that enabled customers to view one anothers' online orders. 
    News stories in the fall of 2003 stated that a manufacturing company recalled all their transportation products in order to fix a software problem causing instability in certain circumstances. The company found and reported the bug itself and initiated the recall procedure in which a software upgrade fixed the problems. 
    In August of 2003 a U.S. court ruled that a lawsuit against a large online brokerage company could proceed; the lawsuit reportedly involved claims that the company was not fixing system problems that sometimes resulted in failed stock trades, based on the experiences of 4 plaintiffs during an 8-month period. A previous lower court's ruling that "...six miscues out of more than 400 trades does not indicate negligence." was invalidated. 
    In April of 2003 it was announced that a large student loan company in the U.S. made a software error in calculating the monthly payments on 800,000 loans. Although borrowers were to be notified of an increase in their required payments, the company will still reportedly lose $8 million in interest. The error was uncovered when borrowers began reporting inconsistencies in their bills. 
    News reports in February of 2003 revealed that the U.S. Treasury Department mailed 50,000 Social Security checks without any beneficiary names. A spokesperson indicated that the missing names were due to an error in a software change. Replacement checks were subsequently mailed out with the problem corrected, and recipients were then able to cash their Social Security checks. 
    In March of 2002 it was reported that software bugs in Britain's national tax system resulted in more than 100,000 erroneous tax overcharges. The problem was partly attributed to the difficulty of testing the integration of multiple systems. 
    A newspaper columnist reported in July 2001 that a serious flaw was found in off-the-shelf software that had long been used in systems for tracking certain U.S. nuclear materials. The same software had been recently donated to another country to be used in tracking their own nuclear materials, and it was not until scientists in that country discovered the problem, and shared the information, that U.S. officials became aware of the problems. 
    According to newspaper stories in mid-2001, a major systems development contractor was fired and sued over problems with a large retirement plan management system. According to the reports, the client claimed that system deliveries were late, the software had excessive defects, and it caused other systems to crash. 
    In January of 2001 newspapers reported that a major European railroad was hit by the aftereffects of the Y2K bug. The company found that many of their newer trains would not run due to their inability to recognize the date '31/12/2000'; the trains were started by altering the control system's date settings. 
    News reports in September of 2000 told of a software vendor settling a lawsuit with a large mortgage lender; the vendor had reportedly delivered an online mortgage processing system that did not meet specifications, was delivered late, and didn't work. 
    In early 2000, major problems were reported with a new computer system in a large suburban U.S. public school district with 100,000+ students; problems included 10,000 erroneous report cards and students left stranded by failed class registration systems; the district's CIO was fired. The school district decided to reinstate it's original 25-year old system for at least a year until the bugs were worked out of the new system by the software vendors. 
    A review board concluded that the NASA Mars Polar Lander failed in December 1999 due to software problems that caused improper functioning of retro rockets utilized by the Lander as it entered the Martian atmosphere. 
    In October of 1999 the $125 million NASA Mars Climate Orbiter spacecraft was believed to be lost in space due to a simple data conversion error. It was determined that spacecraft software used certain data in English units that should have been in metric units. Among other tasks, the orbiter was to serve as a communications relay for the Mars Polar Lander mission, which failed for unknown reasons in December 1999. Several investigating panels were convened to determine the process failures that allowed the error to go undetected. 
    Bugs in software supporting a large commercial high-speed data network affected 70,000 business customers over a period of 8 days in August of 1999. Among those affected was the electronic trading system of the largest U.S. futures exchange, which was shut down for most of a week as a result of the outages. 
    In April of 1999 a software bug caused the failure of a $1.2 billion U.S. military satellite launch, the costliest unmanned accident in the history of Cape Canaveral launches. The failure was the latest in a string of launch failures, triggering a complete military and industry review of U.S. space launch programs, including software integration and testing processes. Congressional oversight hearings were requested. 
    A small town in Illinois in the U.S. received an unusually large monthly electric bill of $7 million in March of 1999. This was about 700 times larger than its normal bill. It turned out to be due to bugs in new software that had been purchased by the local power company to deal with Y2K software issues. 
    In early 1999 a major computer game company recalled all copies of a popular new product due to software problems. The company made a public apology for releasing a product before it was ready. 
    The computer system of a major online U.S. stock trading service failed during trading hours several times over a period of days in February of 1999 according to nationwide news reports. The problem was reportedly due to bugs in a software upgrade intended to speed online trade confirmations. 
    In April of 1998 a major U.S. data communications network failed for 24 hours, crippling a large part of some U.S. credit card transaction authorization systems as well as other large U.S. bank, retail, and government data systems. The cause was eventually traced to a software bug. 
    January 1998 news reports told of software problems at a major U.S. telecommunications company that resulted in no charges for long distance calls for a month for 400,000 customers. The problem went undetected until customers called up with questions about their bills. 
    In November of 1997 the stock of a major health industry company dropped 60% due to reports of failures in computer billing systems, problems with a large database conversion, and inadequate software testing. It was reported that more than $100,000,000 in receivables had to be written off and that multi-million dollar fines were levied on the company by government agencies. 
    A retail store chain filed suit in August of 1997 against a transaction processing system vendor (not a credit card company) due to the software's inability to handle credit cards with year 2000 expiration dates. 
    In August of 1997 one of the leading consumer credit reporting companies reportedly shut down their new public web site after less than two days of operation due to software problems. The new site allowed web site visitors instant access, for a small fee, to their personal credit reports. However, a number of initial users ended up viewing each others' reports instead of their own, resulting in irate customers and nationwide publicity. The problem was attributed to "...unexpectedly high demand from consumers and faulty software that routed the files to the wrong computers." 
    In November of 1996, newspapers reported that software bugs caused the 411 telephone information system of one of the U.S. RBOC's to fail for most of a day. Most of the 2000 operators had to search through phone books instead of using their 13,000,000-listing database. The bugs were introduced by new software modifications and the problem software had been installed on both the production and backup systems. A spokesman for the software vendor reportedly stated that 'It had nothing to do with the integrity of the software. It was human error.' 
    On June 4 1996 the first flight of the European Space Agency's new Ariane 5 rocket failed shortly after launching, resulting in an estimated uninsured loss of a half billion dollars. It was reportedly due to the lack of exception handling of a floating-point error in a conversion from a 64-bit integer to a 16-bit signed integer. 
    Software bugs caused the bank accounts of 823 customers of a major U.S. bank to be credited with $924,844,208.32 each in May of 1996, according to newspaper reports. The American Bankers Association claimed it was the largest such error in banking history. A bank spokesman said the programming errors were corrected and all funds were recovered. 
    On January 1 1984 all computers produced by one of the leading minicomputer makers of the time reportedly failed worldwide. The cause was claimed to be a leap year bug in a date handling function utilized in deletion of temporary operating system files. Technicians throughout the world worked for several days to clear up the problem. It was also reported that the same bug affected many of the same computers four years later. 
    Software bugs in a Soviet early-warning monitoring system nearly brought on nuclear war in 1983, according to news reports in early 1999. The software was supposed to filter out false missile detections caused by Soviet satellites picking up sunlight reflections off cloud-tops, but failed to do so. Disaster was averted when a Soviet commander, based on what he said was a '...funny feeling in my gut', decided the apparent missile attack was a false alarm. The filtering software code was rewritten. 

    Return to top of this page's FAQ list 

    Does every software project need testers? 
    While all projects will benefit from testing, some projects may not require independent test staff to succeed. 

    Which projects may not need independent test staff? The answer depends on the size and context of the project, the risks, the development methodology, the skill and experience of the developers, and other factors. For instance, if the project is a short-term, small, low risk project, with highly experienced programmers utilizing thorough unit testing or test-first development, then test engineers may not be required for the project to succeed. 

    In some cases an IT organization may be too small or new to have a testing staff even if the situation calls for it. In these circumstances it may be appropriate to instead use contractors or outsourcing, or adjust the project management and development approach (by switching to more senior developers and agile test-first development, for example). Inexperienced managers sometimes gamble on the success of a project by skipping thorough testing or having programmers do post-development functional testing of their own work, a decidedly high risk gamble. 

    For non-trivial-size projects or projects with non-trivial risks, a testing staff is usually necessary. As in any business, the use of personnel with specialized skills enhances an organization's ability to be successful in large, complex, or difficult tasks. It allows for both a) deeper and stronger skills and b) the contribution of differing perspectives. For example, programmers typically have the perspective of 'what are the technical issues in making this functionality work?'. A test engineer typically has the perspective of 'what might go wrong with this functionality, and how can we ensure it meets expectations?'. Technical people who can be highly effective in approaching tasks from both of those perspectives are rare, which is why, sooner or later, organizations bring in test specialists. 

    Return to top of this page's FAQ list 

    Why does software have bugs? 
    miscommunication or no communication - as to specifics of what an application should or shouldn't do (the application's requirements). 
    software complexity - the complexity of current software applications can be difficult to comprehend for anyone without experience in modern-day software development. Multi-tier distributed systems, applications utilizing mutliple local and remote web services applications, data communications, enormous relational databases, security complexities, and sheer size of applications have all contributed to the exponential growth in software/system complexity. 
    programming errors - programmers, like anyone else, can make mistakes. 
    changing requirements (whether documented or undocumented) - the end-user may not understand the effects of changes, or may understand and request them anyway - redesign, rescheduling of engineers, effects on other projects, work already completed that may have to be redone or thrown out, hardware requirements that may be affected, etc. If there are many minor changes or any major changes, known and unknown dependencies among parts of the project are likely to interact and cause problems, and the complexity of coordinating changes may result in errors. Enthusiasm of engineering staff may be affected. In some fast-changing business environments, continuously modified requirements may be a fact of life. In this case, management must understand the resulting risks, and QA and test engineers must adapt and plan for continuous extensive testing to keep the inevitable bugs from running out of control - see 'What can be done if requirements are changing continuously?' in the LFAQ. Also see information about 'agile' approaches such as XP, in Part 2 of the FAQ. 
    time pressures - scheduling of software projects is difficult at best, often requiring a lot of guesswork. When deadlines loom and the crunch comes, mistakes will be made. 
    egos - people prefer to say things like: 
      'no problem' 
      'piece of cake'
      'I can whip that out in a few hours'
      'it should be easy to update that old code'

     instead of:
      'that adds a lot of complexity and we could end up
      making a lot of mistakes'
      'we have no idea if we can do that; we'll wing it'
      'I can't estimate how long it will take, until I
      take a close look at it'
      'we can't figure out what that old spaghetti code
      did in the first place'

     If there are too many unrealistic 'no problem's', the
     result is bugs.
     
    poorly documented code - it's tough to maintain and modify code that is badly written or poorly documented; the result is bugs. In many organizations management provides no incentive for programmers to document their code or write clear, understandable, maintainable code. In fact, it's usually the opposite: they get points mostly for quickly turning out code, and there's job security if nobody else can understand it ('if it was hard to write, it should be hard to read'). 
    software development tools - visual tools, class libraries, compilers, scrīpting tools, etc. often introduce their own bugs or are poorly documented, resulting in added bugs. 

    Return to top of this page's FAQ list 

    How can new Software QA processes be introduced in an existing organization? 
    A lot depends on the size of the organization and the risks involved. For large organizations with high-risk (in terms of lives or property) projects, serious management buy-in is required and a formalized QA process is necessary. 
    Where the risk is lower, management and organizational buy-in and QA implementation may be a slower, step-at-a-time process. QA processes should be balanced with productivity so as to keep bureaucracy from getting out of hand. 
    For small groups or projects, a more ad-hoc process may be appropriate, depending on the type of customers and projects. A lot will depend on team leads or managers, feedback to developers, and ensuring adequate communications among customers, managers, developers, and testers. 
    The most value for effort will often be in (a) requirements management processes, with a goal of clear, complete, testable requirement specifications embodied in requirements or design documentation, or in 'agile'-type environments extensive continuous coordination with end-users, (b) design inspections and code inspections, and (c) post-mortems/retrospectives. 
    Other possibilities include incremental self-managed team approaches such as 'Kaizen' methods of continuous process improvement, the Deming-Shewhart Plan-Do-Check-Act cycle, and others. 
    Also see 'How can QA processes be implemented without reducing productivity?' in the LFAQ section. 

    (See the Bookstore section's 'Software QA', 'Software Engineering', and 'Project Management' categories for useful books with more information.) 

    Return to top of this page's FAQ list 

    What is verification? validation? 
    Verification typically involves reviews and meetings to evaluate documents, plans, code, requirements, and specifications. This can be done with checklists, issues lists, walkthroughs, and inspection meetings. Validation typically involves actual testing and takes place after verifications are completed. The term 'IV & V' refers to Independent Verification and Validation. 

    Return to top of this page's FAQ list 

    What is a 'walkthrough'? 
    A 'walkthrough' is an informal meeting for evaluation or informational purposes. Little or no preparation is usually required. 

    Return to top of this page's FAQ list 

    What's an 'inspection'? 
    An inspection is more formalized than a 'walkthrough', typically with 3-8 people including a moderator, reader, and a recorder to take notes. The subject of the inspection is typically a document such as a requirements spec or a test plan, and the purpose is to find problems and see what's missing, not to fix anything. Attendees should prepare for this type of meeting by reading thru the document; most problems will be found during this preparation. The result of the inspection meeting should be a written report. Thorough preparation for inspections is difficult, painstaking work, but is one of the most cost effective methods of ensuring quality. Employees who are most skilled at inspections are like the 'eldest brother' in the parable in 'Why is it often hard for organizations to get serious about quality assurance?'. Their skill may have low visibility but they are extremely valuable to any software development organization, since bug prevention is far more cost-effective than bug detection. 

    Return to top of this page's FAQ list 

    What kinds of testing should be considered? 
    Black box testing - not based on any knowledge of internal design or code. Tests are based on requirements and functionality. 
    White box testing - based on knowledge of the internal logic of an application's code. Tests are based on coverage of code statements, branches, paths, conditions. 
    unit testing - the most 'micro' scale of testing; to test particular functions or code modules. Typically done by the programmer and not by testers, as it requires detailed knowledge of the internal program design and code. Not always easily done unless the application has a well-designed architecture with tight code; may require developing test driver modules or test harnesses. 
    incremental integration testing - continuous testing of an application as new functionality is added; requires that various aspects of an application's functionality be independent enough to work separately before all parts of the program are completed, or that test drivers be developed as needed; done by programmers or by testers. 
    integration testing - testing of combined parts of an application to determine if they function together correctly. The 'parts' can be code modules, individual applications, client and server applications on a network, etc. This type of testing is especially relevant to client/server and distributed systems. 
    functional testing - black-box type testing geared to functional requirements of an application; this type of testing should be done by testers. This doesn't mean that the programmers shouldn't check that their code works before releasing it (which of course applies to any stage of testing.) 
    system testing - black-box type testing that is based on overall requirements specifications; covers all combined parts of a system. 
    end-to-end testing - similar to system testing; the 'macro' end of the test scale; involves testing of a complete application environment in a situation that mimics real-world use, such as interacting with a database, using network communications, or interacting with other hardware, applications, or systems if appropriate. 
    sanity testing or smoke testing - typically an initial testing effort to determine if a new software version is performing well enough to accept it for a major testing effort. For example, if the new software is crashing systems every 5 minutes, bogging down systems to a crawl, or corrupting databases, the software may not be in a 'sane' enough condition to warrant further testing in its current state. 
    regression testing - re-testing after fixes or modifications of the software or its environment. It can be difficult to determine how much re-testing is needed, especially near the end of the development cycle. Automated testing tools can be especially useful for this type of testing. 
    acceptance testing - final testing based on specifications of the end-user or customer, or based on use by end-users/customers over some limited period of time. 
    load testing - testing an application under heavy loads, such as testing of a web site under a range of loads to determine at what point the system's response time degrades or fails. 
    stress testing - term often used interchangeably with 'load' and 'performance' testing. Also used to describe such tests as system functional testing while under unusually heavy loads, heavy repetition of certain actions or inputs, input of large numerical values, large complex queries to a database system, etc. 
    performance testing - term often used interchangeably with 'stress' and 'load' testing. Ideally 'performance' testing (and any other 'type' of testing) is defined in requirements documentation or QA or Test Plans. 
    usability testing - testing for 'user-friendliness'. Clearly this is subjective, and will depend on the targeted end-user or customer. User interviews, surveys, video recording of user sessions, and other techniques can be used. Programmers and testers are usually not appropriate as usability testers. 
    install/uninstall testing - testing of full, partial, or upgrade install/uninstall processes. 
    recovery testing - testing how well a system recovers from crashes, hardware failures, or other catastrophic problems. 
    failover testing - typically used interchangeably with 'recovery testing' 
    security testing - testing how well the system protects against unauthorized internal or external access, willful damage, etc; may require sophisticated testing techniques. 
    compatability testing - testing how well software performs in a particular hardware/software/operating system/network/etc. environment. 
    exploratory testing - often taken to mean a creative, informal software test that is not based on formal test plans or test cases; testers may be learning the software as they test it. 
    ad-hoc testing - similar to exploratory testing, but often taken to mean that the testers have significant understanding of the software before testing it. 
    context-driven testing - testing driven by an understanding of the environment, culture, and intended use of software. For example, the testing approach for life-critical medical equipment software would be completely different than that for a low-cost computer game. 
    user acceptance testing - determining if software is satisfactory to an end-user or customer. 
    comparison testing - comparing software weaknesses and strengths to competing products. 
    alpha testing - testing of an application when development is nearing completion; minor design changes may still be made as a result of such testing. Typically done by end-users or others, not by programmers or testers. 
    beta testing - testing when development and testing are essentially completed and final bugs and problems need to be found before final release. Typically done by end-users or others, not by programmers or testers. 
    mutation testing - a method for determining if a set of test data or test cases is useful, by deliberately introducing various code changes ('bugs') and retesting with the original test data/cases to determine if the 'bugs' are detected. Proper implementation requires large computational resources. 
    (See the Bookstore section's 'Software Testing' category for useful books on Software Testing.) 

    Return to top of this page's FAQ list 

    What are 5 common problems in the software development process? 
    poor requirements - if requirements are unclear, incomplete, too general, and not testable, there will be problems. 
    unrealistic schedule - if too much work is crammed in too little time, problems are inevitable. 
    inadequate testing - no one will know whether or not the program is any good until the customer complains or systems crash. 
    featuritis - requests to pile on new features after development is underway; extremely common. 
    miscommunication - if developers don't know what's needed or customer's have erroneous expectations, problems can be expected. 
    (See the Bookstore section's 'Software QA', 'Software Engineering', and 'Project Management' categories for useful books with more information.) 

    Return to top of this page's FAQ list 

    What are 5 common solutions to software development problems? 
    solid requirements - clear, complete, detailed, cohesive, attainable, testable requirements that are agreed to by all players. In 'agile'-type environments, continuous close coordination with customers/end-users is necessary to ensure that changing/emerging requirements are understood. 
    realistic schedules - allow adequate time for planning, design, testing, bug fixing, re-testing, changes, and documentation; personnel should be able to complete the project without burning out. 
    adequate testing - start testing early on, re-test after fixes or changes, plan for adequate time for testing and bug-fixing. 'Early' testing could include static code analysis/testing, test-first development, unit testing by developers, built-in testing and diagnostic capabilities, automated post-build testing, etc. 
    stick to initial requirements where feasible - be prepared to defend against excessive changes and additions once development has begun, and be prepared to explain consequences. If changes are necessary, they should be adequately reflected in related schedule changes. If possible, work closely with customers/end-users to manage expectations. In 'agile'-type environments, initial requirements may be expected to change significantly, requiring that true agile processes be in place. 
    communication - require walkthroughs and inspections when appropriate; make extensive use of group communication tools - groupware, wiki's, bug-tracking tools and change management tools, intranet capabilities, etc.; ensure that information/documentation is available and up-to-date - preferably electronic, not paper; promote teamwork and cooperation; use protoypes and/or continuous communication with end-users if possible to clarify expectations. 
    (See the Bookstore section's 'Software QA', 'Software Engineering', and 'Project Management' categories for useful books with more information.) 

    Return to top of this page's FAQ list 

    What is software 'quality'? 
    Quality software is reasonably bug-free, delivered on time and within budget, meets requirements and/or expectations, and is maintainable. However, quality is obviously a subjective term. It will depend on who the 'customer' is and their overall influence in the scheme of things. A wide-angle view of the 'customers' of a software development project might include end-users, customer acceptance testers, customer contract officers, customer management, the development organization's management/accountants/testers/salespeople, future software maintenance engineers, stockholders, magazine columnists, etc. Each type of 'customer' will have their own slant on 'quality' - the accounting department might define quality in terms of profits while an end-user might define quality as user-friendly and bug-free. (See the Bookstore section's 'Software QA' category for useful books with more information.) 

    Return to top of this page's FAQ list 

    What is 'good code'? 
    'Good code' is code that works, is reasonably bug free, and is readable and maintainable. Some organizations have coding 'standards' that all developers are supposed to adhere to, but everyone has different ideas about what's best, or what is too many or too few rules. There are also various theories and metrics, such as McCabe Complexity metrics. It should be kept in mind that excessive use of standards and rules can stifle productivity and creativity. 'Peer reviews', 'buddy checks' pair programming, code analysis tools, etc. can be used to check for problems and enforce standards. 
    For example, in C/C++ coding, here are some typical ideas to consider in setting rules/standards; these may or may not apply to a particular situation: 
    minimize or eliminate use of global variables. 
    use descrīptive function and method names - use both upper and lower case, avoid abbreviations, use as many characters as necessary to be adequately descrīptive (use of more than 20 characters is not out of line); be consistent in naming conventions. 
    use descrīptive variable names - use both upper and lower case, avoid abbreviations, use as many characters as necessary to be adequately descrīptive (use of more than 20 characters is not out of line); be consistent in naming conventions. 
    function and method sizes should be minimized; less than 100 lines of code is good, less than 50 lines is preferable. 
    function descrīptions should be clearly spelled out in comments preceding a function's code. 
    organize code for readability. 
    use whitespace generously - vertically and horizontally 
    each line of code should contain 70 characters max. 
    one code statement per line. 
    coding style should be consistent throught a program (eg, use of brackets, indentations, naming conventions, etc.) 
    in adding comments, err on the side of too many rather than too few comments; a common rule of thumb is that there should be at least as many lines of comments (including header blocks) as lines of code. 
    no matter how small, an application should include documentaion of the overall program function and flow (even a few paragraphs is better than nothing); or if possible a separate flow chart and detailed program documentation. 
    make extensive use of error handling procedures and status and error logging. 
    for C++, to minimize complexity and increase maintainability, avoid too many levels of inheritance in class heirarchies (relative to the size and complexity of the application). Minimize use of multiple inheritance, and minimize use of operator overloading (note that the Java programming language eliminates multiple inheritance and operator overloading.) 
    for C++, keep class methods small, less than 50 lines of code per method is preferable. 
    for C++, make liberal use of exception handlers 

    Return to top of this page's FAQ list 

    What is 'good design'? 
    'Design' could refer to many things, but often refers to 'functional design' or 'internal design'. Good internal design is indicated by software code whose overall structure is clear, understandable, easily modifiable, and maintainable; is robust with sufficient error-handling and status logging capability; and works correctly when implemented. Good functional design is indicated by an application whose functionality can be traced back to customer and end-user requirements. (See further discussion of functional and internal design in 'What's the big deal about requirements?' in FAQ #2.) For programs that have a user interface, it's often a good idea to assume that the end user will have little computer knowledge and may not read a user manual or even the on-line help; some common rules-of-thumb include: 
    the program should act in a way that least surprises the user 
    it should always be evident to the user what can be done next and how to exit 
    the program shouldn't let the users do something stupid without warning them. 

    Return to top of this page's FAQ list 

    What is SEI? CMM? CMMI? ISO? IEEE? ANSI? Will it help? 
    SEI = 'Software Engineering Institute' at Carnegie-Mellon University; initiated by the U.S. Defense Department to help improve software development processes. 
    CMM = 'Capability Maturity Model', now called the CMMI ('Capability Maturity Model Integration'), developed by the SEI. It's a model of 5 levels of process 'maturity' that determine effectiveness in delivering quality software. It is geared to large organizations such as large U.S. Defense Department contractors. However, many of the QA processes involved are appropriate to any organization, and if reasonably applied can be helpful. Organizations can receive CMMI ratings by undergoing assessments by qualified auditors. 
      Level 1 - characterized by chaos, periodic panics, and heroic
      efforts required by individuals to successfully
      complete projects. Few if any processes in place;
      successes may not be repeatable.

      Level 2 - software project tracking, requirements management,
      realistic planning, and configuration management
      processes are in place; successful practices can
      be repeated.

      Level 3 - standard software development and maintenance processes
      are integrated throughout an organization; a Software
      Engineering Process Group is is in place to oversee
      software processes, and training programs are used to
      ensure understanding and compliance.

      Level 4 - metrics are used to track productivity, processes,
      and products. Project performance is predictable,
      and quality is consistently high.

      Level 5 - the focus is on continouous process improvement. The
      impact of new processes and technologies can be
      predicted and effectively implemented when required.


      Perspective on CMM ratings: During 1997-2001, 1018 organizations
      were assessed. Of those, 27% were rated at Level 1, 39% at 2,
      23% at 3, 6% at 4, and 5% at 5. (For ratings during the period 
      1992-96, 62% were at Level 1, 23% at 2, 13% at 3, 2% at 4, and 
      0.4% at 5.) The median size of organizations was 100 software 
      engineering/maintenance personnel; 32% of organizations were 
      U.S. federal contractors or agencies. For those rated at 
      Level 1, the most problematical key process area was in 
      Software Quality Assurance.

    ISO = 'International Organisation for Standardization' - The ISO 9001:2000 standard (which replaces the previous standard of 1994) concerns quality systems that are assessed by outside auditors, and it applies to many kinds of production and manufacturing organizations, not just software. It covers documentation, design, development, production, testing, installation, servicing, and other processes. The full set of standards consists of: (a)Q9001-2000 - Quality Management Systems: Requirements; (b)Q9000-2000 - Quality Management Systems: Fundamentals and Vocabulary; (c)Q9004-2000 - Quality Management Systems: Guidelines for Performance Improvements. To be ISO 9001 certified, a third-party auditor assesses an organization, and certification is typically good for about 3 years, after which a complete reassessment is required. Note that ISO certification does not necessarily indicate quality products - it indicates only that documented processes are followed. Also see http://www.iso.org/ for the latest information. In the U.S. the standards can be purchased via the ASQ web site at http://www.asq.org/quality-press/ 
    ISO 9126 defines six high level quality characteristics that can be used in software evaluation. It includes functionality, reliability, usability, efficiency, maintainability, and portability. 
    IEEE = 'Institute of Electrical and Electronics Engineers' - among other things, creates standards such as 'IEEE Standard for Software Test Documentation' (IEEE/ANSI Standard 829), 'IEEE Standard of Software Unit Testing (IEEE/ANSI Standard 1008), 'IEEE Standard for Software Quality Assurance Plans' (IEEE/ANSI Standard 730), and others. 
    ANSI = 'American National Standards Institute', the primary industrial standards body in the U.S.; publishes some software-related standards in conjunction with the IEEE and ASQ (American Society for Quality). 
    Other software development/IT management process assessment methods besides CMMI and ISO 9000 include SPICE, Trillium, TickIT, Bootstrap, ITIL, MOF, and CobiT. 
    See the 'Other Resources' section for further information available on the web. 

    Return to top of this page's FAQ list 

    What is the 'software life cycle'? 
    The life cycle begins when an application is first conceived and ends when it is no longer in use. It includes aspects such as initial concept, requirements analysis, functional design, internal design, documentation planning, test planning, coding, document preparation, integration, testing, maintenance, updates, retesting, phase-out, and other aspects. (See the Bookstore section's 'Software QA', 'Software Engineering', and 'Project Management' categories for useful books with more information.)


  • 判断文件/文件夹是否存在

    2008-08-26 22:13:29

     在日常测试中,可能需要判断生成的文书或者文件夹是否正确存在,而手工去一一验证则工作量比较大而且枯燥。利用脚本实现就比较方便了。具体如下:

    以下是具体的实现代码:
    Set ōbjFSO = CreateObject("scrīpting.FileSystemObject")
    If objFSO.FolderExists("C:\scrīpts") Then
        Wscrīpt.Echo "The folder exists."
    Else
        Wscrīpt.Echo "The folder does not exist."
    End If
     
    判断是否存在指定文件
    Set ōbjFSO = CreateObject("scrīpting.FileSystemObject")
    If objFSO.FileExists("C:\scrīpts.txt") Then
        Wscrīpt.Echo "The file exists."
    Else
        Wscrīpt.Echo "The filedoes not exist."
    End If
    而如果文件夹在远程计算机上,则可以利用以下语句实现:
    strComputer = "atl-ws-01"//计算机名
    Set ōbjWMIService = GetObject _
        ("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colFolders = objWMIService.ExecQuery _
        ("Select * From Win32_Directory Where " & _
            "Name = 'C:\\scrīpts'")
    Wscrīpt.Echo colFolders.Count
    如果不知道文件生成的路径,则可以:
    strComputer = "atl-ws-01"
    Set ōbjWMIService = GetObject _
        ("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colFolders = objWMIService.ExecQuery _
        ("Select * From Win32_Directory Where " & _
            "FileName = 'scrīpts'")
    Wscrīpt.Echo colFolders.Count
  • 检查当前使用用户是否为管理员

    2008-08-25 22:59:18

    Set ōbjNetwork = CreateObject("Wscrīpt.Network")
    strComputer = objNetwork.ComputerName
    strUser = objNetwork.UserName

    Set ōbjGroup = GetObject("WinNT://" & strComputer & "/Administrators")
    For Each objUser in objGroup.Members
      If objUser.Name = strUser Then
      Wscrīpt.Echo strUser & " is a local administrator."
      End If
    Next

    那么,这段脚本做了些什么?好,首先我们创建了 Wscrīpt Network 对象的一个实例;我们可以使用该对象获得计算机及登录用户的名称。

    牢牢掌握了这些名称之后,我们使用 WinNT 提供者绑定到所讨论计算机上的 Administrators 组。然后,我们进入一个 For Each 循环,遍历所有的组成员(Members 属性以数组形式保存,这就是我们为什么需要 For Each 循环的原因)。对于找到的每一位成员,我们检查成员的登录名(objUser.Name)是否等于登录用户的名称(保存在变量 strUser 中)。

    以及该成员的名称是否与登录用户的名称相匹配?如果都满足条件,那么意味着登录用户肯定是一位本地管理员;否则,他(她)不是 Administrators 组的成员。在示例脚本中,我们仅仅显示了用户是否为一名本地管理员;在实际的登录脚本中,您可以更进一步,执行一些要求管理员权限的任务。

  • What is "Software Testing Life Cycle"?

    2008-08-22 09:11:12

    The software testing life cycle is a parallel,or integrated,process which aligns with the software development lifecycle and picks up the test activities as
    a sequence of events,that may be managed seperately. this alignment may vary depending on the development method used (iterative,spiral,agile,RAD,DSDM,RUP).
      When you work to a waterfall development method,The STLC may be follow:
    STLC Phases
     - Proposal/Contract
     - Testing Requirements Specification(TRS)
     - Design 
     - Testing
     - Inspection and Release
     - Client Acceptance
     
    Proposal/Contract
    1) Analyze Scope of Project
    2) Prepare Contract
    3) Review of Contract
    4) Release
    5) Return to Top
     
    Testing Requirements Specification (TRS)
    1) Analysis
    2) Product requirements document(产品文档)
    3) Develop risk assessment criteria(确定风险评估标准)
    4) Identify acceptance criteria(确定验收标准)
    5) Document product Definition, Testing Strategies.(文档化产品定义,测试策略)
    6) Define problem reporting procedures
    7) Planning
    8) Schedule
    9) Return to Top
     
    Design
    Preparation of Master Test Plan 
    Setup test environment 
    High level test plan 
    Design Test plans, Test Cases 
    Decide if any set of test cases to be automated 
    Return to Top 
     
    Testing
    Planning 
    Testing - Initial test cycles, bug fixes and re-testing 
    Final Testing and Implementation 
    Setup database to track components of the automated testing system, i.e. reusable modules 
    Return to Top 
     
    Inspection and Release
    Final Review of Testing 
    Metrics to measure improvement 
    Return to Top 
     
    Client Acceptance
     
    Replication of Product Product Delivery Records Submission Client Sign-off


  • what is a bug?

    2008-08-21 11:41:00

     a software bug occurs when one or more of the following five rules is true: 
      1) The software doesn't do something that product specification says it should do.
      2) The software does somethinng that product specification says it shouldn't do
      3) The software does somerhing that product specification doesn't mention(提及)
      4) The software doesn't do something that product specification doesn't mention but should do.
      5) The sofrware is difficult to understand,hard to use,slow or --in the software tester's eyes -- will
    be viewed by the end user as just plain not right.
                                                    --摘自《Software Testing》

  • 列出Windows服务,并填充到word中

    2008-08-18 16:55:20

      直接把代码复制到文本中,后缀改为.vbs,双击即可运行,也可以复制到测试工具中运行

    ' Add a Formatted Table to a Word Document


    Set ōbjWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set ōbjDoc = objWord.Documents.Add()

    Set ōbjRange = objDoc.Range()
    objDoc.Tables.Add objRange,1,3
    Set ōbjTable = objDoc.Tables(1)

    x=1

    strComputer = "."
    Set ōbjWMIService = _
      GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_Service ")
    For Each objItem in colItems
      If x > 1 Then
      objTable.Rows.Add()
      End If
      objTable.Cell(x, 1).Range.Font.Bold = True
      objTable.Cell(x, 1).Range.Text = objItem.Name
      objTable.Cell(x, 2).Range.text = objItem.DisplayName
      objTable.Cell(x, 3).Range.text = objItem.State
      x = x + 1
    Next

793/4<1234>
Open Toolbar