Custom Search

Saturday, January 9, 2010

Python Regular expression pattern special sequences

In Table 1-18, "C" is any character, "R" is any regular expression form in the left column of the table, and "m" and "n" are integers. Each form usually consumes as much of the string being matched as possible, except for the nongreedy forms (which consume as little as possible, as long as the entire pattern still matches the target string).

Table 1-18. Regular expression pattern syntax

Form

Description

.

Matches any character (including newline if DOTALL flag is specified).

^

Matches start of string (of every line in MULTILINE mode).

$

Matches end of string (of every line in MULTILINE mode).

C

Any nonspecial character matches itself.

R*

Zero or more occurrences of preceding regular expression R (as many as possible).

R+

One or more occurrences of preceding regular expression R (as many as possible).

R?

Zero or one occurrence of preceding regular expression R.

R{m,n}

Matches from m to n repetitions of preceding regular expression R.

R*?, R+?, R??, R{m,n}?

Same as *, +, and ? but matches as few characters/times as possible; nongreedy.

[...]

Defines character set; e.g., [a-zA-Z] matches all letters (also see Table 1-19).

[^...]

Defines complemented character set: matches if character is not in set.

\

Escapes special characters (e.g., *?+|( )) and introduces special sequences (see Table 1-19). Due to Python rules, write as \\ or r'\\'.

\\

Matches a literal \; due to Python string rules, write as \\\\ in pattern, or r'\\'.

R|R

Alternative: matches left or right R.

RR

Concatenation: matches both Rs.

(R)

Matches any RE inside ( ), and delimits a group (retains matched substring).

(?: R)

Same as (R) but doesn't delimit a group.

(?= R)

Look-ahead assertion: matches if R matches next, but doesn't consume any of the string (e.g., X (?=Y) matches X if followed by Y.

(?! R)

Negative look-ahead assertion: matches if R doesn't match next. Negative of (?=R).

(?P R)

Matches any RE inside ( ) and delimits a named group (e.g., r'(?P[a-zA-Z_]\ w*)' defines a group named id).

(?P=name)

Matches whatever text was matched by the earlier group named name.

(?<= R)

Positive look-behind assertion: matches if preceded by a match of fixed-width R.

(?

Negative look-behind assertion: matches if not preceded by a match of fixed-width R.

(?#...)

A comment; ignored.

(?letter)

letter is one of "i", "L", "m", "s", "x", or "u". Set flag (re.I, re.L, etc.) for entire RE.

In Table 1-19, \b, \B, \d, \D, \s, \S, \w, and \W behave differently depending on flags: if LOCALE (?L) is used, they depend on the current 8-bit locale; if UNICODE (?u) is used, they depend on the Unicode character properties; if neither flag is used, they assume 7-bit U.S. ASCII. Tip: use raw strings (r'\n') to literalize backslashes in Table 1-19 class escapes.

Table 1-19. Regular expression pattern special sequences

Sequence

Description

\num

Matches text of the group num (numbered from 1)

\A

Matches only at the start of the string

\b

Empty string at word boundaries

\B

Empty string not at word boundary

\d

Any decimal digit (like [0-9])

\D

Any non-decimal digit character (like [^0-9])

\s

Any whitespace character (like [ \t\n\r\f\v])

\S

Any non-whitespace character (like [^ \t\n\r\f\v])

\w

Any alphanumeric character

\W

Any non-alphanumeric character

\Z

Matches only at the end of the string



*************** FROM PERL (common) *************

my $str = "Hello saju how are you" # Declaring and initializing a variable '$str'.

## Finding ##
$str =~ /pattern/ # Equivalent to function 'regmatch(pattern,$str)'.
Example: $str =~ /saju/ # Finding for pattern 'saju' in variable '$str'.

## Finding and substituting or replacing ##
$str =~ s/pattern/replacement/ # Equivalent to function 'regsubstitute(pattern,replacement,$str)'.
Example: $str =~ s/saju/sanu/ # Finding for pattern 'saju' in variable '$str' and replace it with 'sanu'.

***************************************

# Regular expression is written in between / ... /.
# A few 11 characters mean something special in between / ... / , they are
[], {}, (), *, +, ?, ., \, ^, $, |
# Other characters in between / ... / just means themselves.

# \ ---> Backslash removing special meaning of special characters in between / ... / s

**************************************************************
### Character Classes ###

[aeiou] ---> Match any one of these characters a,e,i,o,u.
Example: /p[aeiou]t/ matches pat,pet,pit,pot,put.
Example: /p[^aeiou]t/ it not maches pat,pet,pit,pot,put.But it maches pbt,pct,pdt,----.

## character class shortcuts ##

[0123456789] ----> \d
[abc..xyxABC...XYZ0123456789_] ----> \w # Except white space.
[ \n\r\t\f] ----> \s # White space charater class.

[^0123456789] ----> \D
[^abc..xyxABC...XYZ0123456789_] ----> \W
[^ \n\r\t\f] ----> \S # opposite of White space charater class.

. ---> 'dot' shortcut matches any character(whilte space character,abc---xyzADC---XYZ0123456789_).It is widely used.

## character class shortcuts Examples ##

/\d\d-\d\d-\d\d\d\d/ ---> 12-11-2009
/\d\d\/\d\d\/\d\d\d\d/ ---> 11/10/2009
#or
m{\d\d/\d\d/\d\d\d\d} ---> 11/10/2009 # This method is used to avoid usage of delimiter Backslash '\' .Here we using m{..} sinstead of /../.

***************************************
### Quantifiers ###

# Normally, we match exactly one (thing)literal character or character class.
# Put a quantifier after a (thing) literal character or character class to change that.
# We can say we want to match
1) Zero or one (thing) literal character or character class. ---> ?
2) Zero or more (thing) literal character or character class. ---> *
3) One or more (thing) literal character or character class. ---> +

## Zero or One thing --> ? ##

/sa?ju/ ----> Matches 'saju', 'sju'. Here literal character 'a' matches Zero or One time. Not matches 'saaju'.

/s[aj]?u/ ----> Matches 'sju', 'sau', 'su'. Not matches 'saju'.Here characters in the character class '[aj]' matches Zero or One time,

## Zero or More thing --> * ##

/sa*ju/ ----> Matches 'saju', 'sju', 'saaaju', etc. Here literal character 'a' matches Zero or More times.

/s[aj]*u/ ----> Matches 'saaaju', 'sjjju', 'saaajjju', 'su', 'saju', 'sajajaajju'.Here characters in the character class '[aj]' matches Zero or More times.

## One or More thing --> + ##

/sa+ju/ ----> Matches 'saju', 'saaaju'. Not matches 'sju'. Here literal character 'a' must matches One or More times.

/s[aj]+u/ ----> Matches 'saju', 'saaaju', 'sajjju', 'saaajjju', sajajaajju'. Not matches 'su'.Here characters in the character class '[aj]' must matches One or More times.

## Without Qualifiers ##

/(s[aj]u)/ ----> Matches 'sau', 'sju'. Not matches 'saju','su'.

***************************************
### Anchors ###

\A ---> Matches only at te begining of the text.It must be first thing in Regular Expression.

\Z ---> MAtches only at the end, or newline followed by end. It must be last thing in Regular Expression.

Examples:

/\A\d+/ ---> Line start with digits.

/\s\d{5}\Z/ ----> Line end with space and 5 digits.

***************************************
### Capturing Groups ###

# Parentheses '()' capture whatever they match in $1,$2,----.
# Count left-most parentheses to get corresponding $n.

Example:

/\A(\w+),\s+([A-Z][A-Z])\s+(\d{5})\Z/ then,

print "City: $1 , State: $2 , Zip: $3 ";

***************************************


Sunday, January 3, 2010

PyS60 Tutorial - Setting the application's orientation

PyS60 Tutorial - Setting the application's orientation

------------------------------------

#Setting the application's orientation

#From S60 3rd edition onwards you can set the orientation of the screen

/************ Complete Source Code Start *************/


import appuifw, e32

#Define the exit function
def quit():
app_lock.signal()


appuifw.app.exit_key_handler=quit

appuifw.app.orientation='landscape'
#or, after waiting 5 seconds
e32.ao_sleep(5)
appuifw.app.orientation='portrait'

app_lock=e32.Ao_lock()
app_lock.wait()

/************ Complete Source Code End *************/

PyS60 Tutorial - Setting the application's screen size

PyS60 Tutorial - Setting the application's screen size

------------------------------------

#Setting the application's screen size

#The available screen sizes are Normal, Large (meaning that only the softkeys pane is visible) and Full

/************ Complete Source Code Start *************/


import appuifw, e32

#Define the exit function
def quit():
app_lock.signal()


appuifw.app.exit_key_handler=quit

#For normal:
appuifw.app.screen="normal"
e32.ao_sleep(5)

#For large:
appuifw.app.screen="large"
e32.ao_sleep(5)

#For full:
appuifw.app.screen="full"

app_lock=e32.Ao_lock()
app_lock.wait()

/************ Complete Source Code End *************/

PyS60 Tutorial - Content Queries

PyS60 Tutorial - Content Queries

------------------------------------

# using this you can store the information entered by the user in a variable.


/*********** Description Start *************/


import appuifw


#asks for a number, in this case integer; for a fractional number use "float"
inf=appuifw.query(u"Enter a number", "number")

#asks for a text
inf=appuifw.query(u"Enter a word", "text")

#asks for a password, and shows the characters as "*" for protection
inf=appuifw.query(u"Enter a password", "code")

#asks for a time in hh:mm format
inf=appuifw.query(u"Enter a time", "time")

#displays a question, the returned values being 1 if the user has selected "Yes" and 0 if the user has selected "No"
inf=appuifw.query(u"Would you like to play again?", "query")

#asks for two fields of information
inf=appuifw.multi_query(u"Part1", u"Part2")

/*********** Description End *************/

/*********** Example 1 Start *************/

import appuifw,e32

def quit():

app_lock.signal()

appuifw.app.exit_key_handler=quit

# Declaring an empty tuple ‘data’

data={}

data['name'] = appuifw.query(u"Enter Name", "text")
data['age'] = appuifw.query(u"Enter age", "number")

data['username'] = appuifw.query(u"Enter UserName", "text")

data['password'] = appuifw.query(u"Enter password", "code")

data['time'] = appuifw.query(u"Enter time", "time")

data['agree'] = appuifw.query(u"Are you agree our terms and conditions?", "query")

if(data['agree']==1):

for key in data:

print key + " : " , data[key]

print "Registration Success"

else:

print "Registration failed"

print "Please agree to continue"

app_lock=e32.Ao_lock()

app_lock.wait()

OUTPUT

----------

name : sanju

age : 22

username : sanju123

password : 123456

time : 12:30

agree : 1

Registration Success

/*********** Example 1 End *************/

PyS60 Tutorial - Content handler

PyS60 Tutorial - Content handler

------------------------------------


# For Open any supported file type with its designated application


/************ Complete Source Code End *************/


import appuifw

a=appuifw.Content_handler()


a.open("C:\\movie.mpg")


#This opens the video file with RealPlayer, or whatever the default player is

/************ Complete Source Code End *************/

PyS60 Tutorial - Canvas

PyS60 Tutorial - Canvas

------------------------------------

#Canvas

#The application's body can be set to Canvas, which is used mainly for displaying images

/************ Complete Source Code Start *************/

import appuifw, graphics, e32

def quit():

app_lock.signal()

appuifw.app.exit_key_handler=quit

def handle_redraw(rect):

c.blit(myimage)

myimage=graphics.Image.open("C:\\myimage.jpg")

c = appuifw.Canvas(event_callback=None, redraw_callback=handle_redraw)

appuifw.app.body=c

app_lock=e32.Ao_lock()

app_lock.wait()

/************ Complete Source Code End *************/

/*********** Description Start *************/

import appuifw, graphics, e32

#Define the exit function

def quit():

app_lock.signal()

appuifw.app.exit_key_handler=quit

#We define a method that will place the image 'myimage' on the canvas:

def handle_redraw(rect):

c.blit(myimage)

# We can make a blank one, specifying its size in pixels

#myimage=graphics.Image.new((240,320))

#We open myimage

myimage=graphics.Image.open("C:\\myimage.jpg")

#This sets ‘c’ as a canvas which can be redrawn and can be modified if certain events (in this case key presses) occur if you make a method for that

c = appuifw.Canvas(event_callback=None, redraw_callback=handle_redraw)

# Setting default body of the application to ‘c’.

appuifw.app.body=c

#c.text((20,30), u"something", font="title")

#Here the text is displayed at the specified coordinates on the canvas, with the title font, if the 1 button is pressed

#Other font types are normal, default, dense, symbol, annotation, and legend. You can also use other formats, as is explained below

#As you've seen above, you can write text on a canvas.

#An additional way of specifying the parameters is:

#c.text((2,24), u'Hello', 0x008000, font=(u'Nokia Hindi S60',48,appuifw.STYLE_BOLD))

#Here 0x008000 is the color of the text, 48 is its size and appuifw.STYLE_BOLD is its style

#The canvas can also be cleared (and optionally filled with a color)

#c.clear()

#c.clear(0x008000) fills it with green

app_lock=e32.Ao_lock()

app_lock.wait()

/*********** Description End *************/

/*********** Note Start *************/

---------------------------------------------------------

Canvas is a UI control that provides a drawable area on the screen and support for handling raw key events .

Canvas([redraw_callback=None, event_callback=None])

Constructs a Canvas object. The optional parameters are callbacks or functions or callable objects that are called when specific events occur. redraw_callback is called whenever a part of the Canvas has been obscured by something, is then revealed, and needs to be redrawn. This can typically happen, for example, when the user switches away from the Python application and back again, or after displaying a pop-up menu. The callback takes as its argument a four-element tuple that contains the top-left and the bottom-right corner of the area that needs to be redrawn. In many cases redrawing the whole Canvas is a reasonable option.

The event_callback is called whenever a raw key event is received. There are three kinds of key events: EEventKeyDown, EEventKey, and EEventKeyUp. When a user presses a key down, events EEventKeyDown and EEventKey are generated. When the key is released, an EEventKeyUp event is generated.

The argument to the event_callback is a dictionary that contains the following data for key events:

# 'type': one of EEventKeyDown, EEventKey, or EEventKeyUp

# 'keycode': the keycode of the key

# 'scancode': the scancode of the key

# 'modifiers': the modifiers that apply to this key event

------------------------------------------------------------

Image Image.open(filename)

Returns a new Image object (mode RGB16) that contains the contents of the named file. The supported file formats are JPEG and PNG. The file format is automatically detected based on file contents. filename should be a full path name.

------------------------------------------------------------

blit(image[,target=(0,0),source=((0,0),image.size),mask=None,scale=0])

Copies the source area from the given image to the target area in this drawable. The source area is copied in its entirety if mask is not given or is set to None. If the mask is given, the source area is copied where the mask is white. mask can be either None or a 1-bit (black and white) image and must be of the same size as the source image.

target and source specify the target area in this image and the source area in the given source. They are coordinate sequences of one or two coordinates. If they specify one coordinate, it is interpreted as the upper-left corner for the area; if they specify two coordinates, they are interpreted as the top-left and bottom-right corners of the area.

If scale is other than zero, scaling is performed on the fly while copying the source area to the target area. If scale is zero, no scaling is performed, and the size of the copied area is clipped to the smaller of source and target areas.

Note that a blit operation with scaling is slower than one without scaling. If you need to blit the same Image many times in a scaled form, consider making a temporary Image of the scaling result and blitting it without scaling. Note also that the scaling performed by the blit operation is much faster but of worse quality than the one done by the resize method, since the blit method does not perform any antialiasing.

------------------------------------------------------------

/*********** Note End *************/

Python function with global and local variables

Python function with global and local variables

Global and Local variable scope inside and outside the python functions

==========================================

balance = 1000

def deposit(amount):

global balance

balance = balance + amount

def withdraw(amount):

global balance

balance = balance - amount

We first create a variable called balance initialized with the value 1000 (say we have 1000 Rupees

balance initially). Then we define two simple functions deposit and withdraw. The interesting

things about these functions are:

• Both functions do not use return

• There is a new keyword in the body of both functions - global

The line:

global balance

simply tells Python that the variable balance being used in the next line (and all the other lines of

the function, if any) refers to the variable balance declared outside the function (such variables are

called global variables in programming language terminology).

The two functions above (deposit and withdraw) are said to have a side effect - in this case, the side

effect is altering the value of a global variable.

==========================================

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely,

all variable assignments in a function store the value in the local symbol table; whereas variable references (search) first

look in the local symbol table, then in the global symbol table, and then in the table of built-in names. Thus, global variables

cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is

called; thus, arguments are passed using call by value (where the value is always an object reference (address), not the value

of the object).4.1 When a function calls another function, a new local symbol table is created for that call.

========================================== Example of python function

balance = 1000

k=100

def deposit(amount):

global balance

balance = balance + amount

# Here 'k' is a local variable to function,so we can assign value to it and modify.

k=50

# Printing value of local variable 'k'.

print 'Local k : ',k

def withdraw(amount):

global balance

balance = balance - amount

# Accessing global variable 'k' that is not local to this function.That is we can only access it value,not modify.

print 'Accessing global k : ',k+30

#But we can assign value to global variable 'balance', because 'balance' is declared as global variable inside the function.

#k = 20 <---- Error, uncommenting this line cause error on above line print 'Accessing global k : ',k+30

print "Balance : ",balance

deposit(100)

print " Balance After Deposit : ",balance

withdraw(200)

print " Balance After Withdraw : ",balance

print 'Value of k : ',k

OUTPUT

-------------

Balance : 1000

Local K : 50

Balance After Deposit : 1100

Accessing global k : 130

Balance After Withdraw : 900

Value of k : 100

==========================================

PyS60 Tutorial - Forms

PyS60 Tutorial - Forms

/************ Complete Source Code Start *************/

import appuifw, e32

#Define the exit function

def quit():

app_lock.signal()

appuifw.app.exit_key_handler=quit

#Create a list to be used in 'combo' selection mode

model=[u'6630', u'E90', u'7610', u'N95', u'N73']

#Define the field list (consists of tuples: (label, type ,value)); label is a unicode string

#Type is one of the following strings: 'text', 'number', 'date', 'time',or 'combo'

data=[(u'Mobile','text', u'Nokia'),(u'Model','combo', (model,0)),(u'Amount','number', 5),(u'Date','date'),(u'Time','time')]

#Set the view/edit mode of the form

flags=appuifw.FFormEditModeOnly

#Create an instance of the form

f=appuifw.Form(data, flags)

#Make the form visible on the UI

f.execute()

app_lock=e32.Ao_lock()

app_lock.wait()

/************ Complete Source Code End *************/

/*********** Description Start *************/

import appuifw, e32

#Define the exit function

def quit():

app_lock.signal()

appuifw.app.exit_key_handler=quit

# Create a list to be used in 'combo' selection mode

# Create a list 'model' to used in 'combo' as values

model=[u'6630', u'E90', u'7610', u'N95', u'N73']

# Define the field list 'data' (consists of tuples: (label, type ,value)); label is a unicode string

# Type is one of the following strings: 'text', 'number', 'date', 'time',or 'combo', value is the value

# to be displayed in the corresponding field,

# 'text' -------> text field

# 'number' -------> number field

# 'date' -------> date field

# 'time' -------> time field

# 'combo' -------> combo box

data=[(u'Mobile','text', u'Nokia'),(u'Model','combo', (model,0)),(u'Amount','number', 5),(u'Date','date'),(u'Time','time')]

# Set the view/edit mode of the form

# Here setting the attribute 'flags' to Ediit mode only for Form type object.

# We can use any name for 'flags'. 'flags' is a default argument to Form, see syntax of form.

# This flag is defined in the module appuifw, So we can directly access it using module name.

flags=appuifw.FFormEditModeOnly

# Create an instance or object of the Form Type

# Passing field list 'data' and flag 'flags' as argument

f = appuifw.Form(data, flags)

# Make the form (form object) visible on the UI

f.execute()

app_lock=e32.Ao_lock()

app_lock.wait()

/*********** Description End *************/

/*********** Note Start *************/

----------------------------------------------------------

Form implements a dynamically configurable, editable multi-field dialog. Form caters for advanced dialog use cases with

requirements such as free selectability of the combination of fields, possibility of validating the user input, and automatically

producing the contents of some dialog fields before allowing the closing of the dialog.

Form([fields=field_list, flags=flag])

For creates a Form instance (object).

# field_list consists of tuples: (label, type [,value]), where

# label is a Unicode string

# type is one of the following strings: 'text', 'number', 'date', 'time',or 'combo'

# value, depending on type: Unicode string, numeric, float (seconds since Unix epoch rounded down to the nearest local midnight),

float (seconds since local midnight), or ([unicode_string choices], index)

Form can also be configured and populated after construction. The configuration flags are visible as an attribute. Form implements

the list protocol that can be used for setting the form fields, as well as obtaining their values after the dialog has been executed.

----------------------------------------------------------

Some of the attributes of the Form instance or object

This 'flags' attribute of Form Type object holds the values of the various configuration flags. Currently supported flags are:

FFormEditModeOnly

When this flag is set, the form remains in edit mode while execute runs.

This flag is defined in the module appuifw, So we can directly access it using module name.

----------------------------------------------------------

/*********** Note End *************/