30 Jul 2008

旧将撼主:新的cuil搜索引擎对抗google

在网络世界中,谷歌无疑是搜索引擎网站的巨头。但几位来头不小的谷歌“叛将”却在7月28日推出新搜索引擎Cuil(发音与“cool”相同)来挑战旧 主。据Cuil声称,他们可以搜到1200亿个页面,大约是谷歌的3倍,绝对是网络搜索的利器。不过,有分析则称,虽然Cuil风头很盛,但要马上威胁到 谷歌的地位仍不现实。(网站地址:www.cuil.com)

##CONTINUE##

Cuil由Googlebase前首席技术官安娜·帕特森与她的丈夫科斯泰罗联手创办,他们的两位亲密助手拉塞尔·帕威尔和路易斯·蒙尼尔同样也曾是谷歌 的资深员工。其中,帕特森来头最大,她在此前曾一手建立起功能强劲的搜索引擎Recall,并在2004年被谷歌连人带网站高价收购。2006 年,更喜欢独自高飞的帕特森辞职,并开始创建Cuil。而协助IBM构建新型搜索引擎WebFountain的丈夫科斯泰罗也成为她最有力的帮手。

29 Jul 2008

pylab: draw circle

借助matlab中最强有力的函数--help,终于在pylab里画了一个圆,matlab也真是,没有自带的circle函数,还得自己写.真是麻烦.先来matlab里的画圆函数:
THETA=linspace(0,2*pi,NOP);
RHO=ones(1,NOP)*radius;
[X,Y] = pol2cart(THETA,RHO);
X=X+center(1);
Y=Y+center(2);
H=plot(X,Y,style);
axis square;
##CONTINUE##
照猫画虎,来段python的,可惜pylab没有做实pol2cart这个函数,没办法,照着思路自己来吧:
用linspace产生0-2*pi的连续角度,然后计算x,y,最后加上圆心坐标,再给plot就行了.

def myCircle(center,radius,NOP=100):
theta = linspace(0,2*pi,NOP)
x=radius * cos(theta) + center[0]
y=radius * sin(theta) + center[1]
return plot(x,y)

28 Jul 2008

python GUI interface introduction

These days, I was working on the disertation which involved with some algorithms implementations. During the period, I need to analysis the results by visual pictures. However, as a newbie with python, I have two choices: Tkinter and wxPython. I will try to write some posts about both of these choices.

For wxPython, I will focus on the combination of matplotlib and wxPython, for my work is mainly involved with matplotlib.
##CONTINUE##

Matplotlib: matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. matplotlib can be used in python scripts, the python and ipython shell (ala matlab or mathematica), web application servers, and six graphical user interface toolkits.

The latest release of Matplotlib is 0.98.1, it requires python2.4 or 2.5 and numpy 1.1. You can download them from internet if you need.

19 Jul 2008

ZT: python黑板报

1. 关于python的启动
除了直接启动进入解释器之外(不要忘记文件结束符是^Z(win)和^D(*nix/Mac)),另外两种方法也很常用:
python -c "a=int(raw_input('a=')); print a*3"
这是直接执行python语句而不必事先写程序。注意整体用双引号,python语言内部用单引号以免引起混淆。
python -i test.py
执行完后回到解释器。注意-i必须在test.py之前。这个方法也适合-c的情形,如:
python -i -c "a=3"
需要注意的是不要用重定向 python <>

2. 脚本的命令行参数
存在sys.argv里。这是一个list.

3. 注释
以#开头,类似于C的//,为单行注释。

4. 输出
用print. 注意复杂类型也可以直接打印,例如list. 比如
import sys
print sys.argv
最后加个逗号可以避免换行。注意每个逗号后实际被追加了一个空格。
print 'a',
print 'b'
由于python有自省功能,也可以打印变量的类型。
print type(sys.argv)
利用解释器学习python的时候可以多用type(_)来确认上一次运行结果的类型。

5. 赋值
和一般的语言一样,且可以是多重的,如
x = y = z = 0

6. 数值类型
整数、浮点数和复数都是支持的。

* 整数没有大小限制:
print 111111111*111111111
print int('12345678987654321')

* 浮点数使用硬件IEEE浮点类型。
print 1.0/3
print float('0.123') # constructor
print 0.1+0.1+0.1-0.3 # not zero!

* 高精度十进制浮点数在decimal模块的Decimal类:
import decimal;
from decimal import Decimal
print Decimal(1)/Decimal(7)
decimal.getcontext().prec = 100 # change precision. default is 28
print Decimal(1)/Decimal(7)
print Decimal('0.1')+Decimal('0.1')+Decimal('0.1')-Decimal('0.3') # exactly zero

* 复数的实部和虚部都是float. 虚数单位用j或者J表示。
a=3+4j
print a.real
print a.imag
print abs(a)

7. 字符串
字符串常量可以用单引号、双引号括起来,也可以用raw字符串r""或者多行串(用"""或者'''包围)。
字符串是不可变的。
print 'a' + 'b' # ab
print 'a' * 3 # aaa
print 'abcd'[2] # c
print len('asdf') # 4
其中第3种用法在C里是无效的。
slicing总是从左到右的,且都是左闭右开区间,因此[-2:]是最后两个字符。

8. 字符串方法分类
判断类
* isalnum()/isalpha()/isdigit()/islower()/isspace()/istitle()/isupper()

查找类
* endswith/startswith(s[,star[,end]]) # 返回bool型
* find/rfind/count(sub[,start[,end]])

变换
* expandtabs([tabsize]) # tabsize默认为8
* replace(old,new[,count]) # 替换所有。如果有count, 则只替换前count个
* ljust/rjust(width[,fillchar])
* lower()/upper()/capitalize()/swapcase()/title()
* lstrip([chars])/rstrip([chars])/strip([chars])

Token处理类
* partition/rpartition(sep) # 从第一次/最后一次出现处分开 e.g 'abc!=12'.partition('!=') returns ('abc','!=','12')
* split/rsplit(sep[,maxsplit]) # 'a--b---c'进行左/右split的结果不一样. 默认是strip后用连续空格隔开
* join(seq) # e.g '-'.join(['a','b','c']) returns 'a-b-c'

8. 字符串格式化
格式化运算符为%,适用于str和unicode,格式为format % values。当要求单参数时values必须是非元组对象,否则
values必须是一个元组(个数和format的需要保持一致),或一个映射(如字典)。例:
print '%(language)s has %(#)03d quote types.' % \
{'language': "Python", "#": 2}


9. 序列操作
参考:Library Reference的3.6节.
python有六种序列类型:str, unicode, list, tuple, buffer, xrange.
大多数序列都有以下操作:x in s, x not in s, s+t, s*n, n*s, s[i], s[i:j], s[i:j:k], len(s), min(s), max(s). i,j,n是整数。
注意乘法(重复操作)是浅拷贝,因此lists=[[]]*3;lists[0].append(3)后得到的是[[3],[3],[3]].
str的in/not in操作可以用来作模式匹配,而不仅仅用来查找单个字符。

10. 列表
列表(lists)是最常用的序列类型,它的各个元素不必有相同的类型。
列表是可变的,甚至可以对它的slice赋值。一些经典的例子。
>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> # Insert (a copy of) itself at the beginning
>>> a[:0] = a
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
>>> # Clear the list: replace all items with an empty list
>>> a[:] = []
>>> a
[]

11. 基本控制流
注意python是靠的缩进而不是begin/end或者{}来指定的语句块。语句块至少要有一条语句,如果实在不需要的话用pass
* while语句
while b > 0:
b--

* if-elif-else语句
注意,没有C中的switch。
if x < y =" -x" x ="="" y =" 0" y =" x

* for语句
是在一个序列中迭代。
a = ['cat', 'dog', 'bird']
for x in a:
print x, len(x)
注意在迭代的时候修改list很不安全,这时可以迭代它的一个备份,如:

>>> for x in a[:]: # make a slice copy of the entire list
... if len(x) > 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']

如果要迭代下标,经常用range函数:
for i in range(len(a)):
print i, a[i]

* break和continue
break和continue的用法一样,但是从break退出和自然推出(for的元素迭代完毕; while的条件为假)是
不一样的。自然退出将执行else语句,这里是一个很好的例子:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell through without finding a factor
print n, 'is a prime number'

18 Jul 2008

conditional operator/ternary operator in python

25.04.2009更新:
a and b or c,必须保证b是true,否则有误.

很多语言种都有这样一个三目运算符,bool ? a : b,使用也很方便,bool为true返回a,否则返回b,python中需要使用and or这两个东东达到同样的效果,实际上python中的逻辑运算符挺让人头疼的。

举个简单的例子:

python 代码
>>> a = "first"
>>> b = "second"

>>> 1
and a or b
'first'
>>> 0 and a or b
'second'

上面的这段代码就是等同三目运算符的了.

and操作会依次比较各个表达式,返回第一个为false的表达式,否则返回最后一个为true的表达式
or操作刚好相反,返回第一个为true的表达式,否则返回最后一个为false的表达式

这样在看上面的代码就容易多了

Example code的脚本中有这么一段

python 代码
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)


很好的利用了and和or的用法,可以根据collapse的值来给前面的函数附值,多么方便


update:

如果你来自 C/C++ 或者是 Java 世界, 那么你很难忽略的一个事实就是 Python 在很长的一段时间里没有条件表达式(C ? X : Y), 或称三元运算符. ( C 是条件表达式; X 是 C 为 True 时的结果, Y 是 C 为 False 时的结果) 贵铎·范·罗萨姆一直拒绝加入这样的功能, 因为他认为应该保持代码简单, 让程序员不轻易出错. 不过在十年多后, 他放弃了, 主要是因为人们试着用and 和 or 来模拟它, 但大多都是错误的. 根据 FAQ , 正确的方法(并不唯一)是(C and [X] or [Y])[0] . 唯一的问题是社区不同意这样的语法. (你可以看一看 PEP 308, 其中有不同的方案.) 对于Python 的这一问题,人们表达了极大的诉求.
贵铎·范·罗萨姆最终选择了一个最被看好(也是他最喜欢)的方案, 然后把它运用于标准库中的一些模块. 根据 PEP , "这个评审通过考察大量现实世界的案例, 包含不同的应用, 以及由不同程序员完成的代码." 最后 Python 2.5 集成的语法确定为: X if C else Y .

17 Jul 2008

Python file operations

file is a special class in Python. Everything is object in python, so is file. It has attributes and methods. Now, let's study something about file:

file(name[, mode[, buffering]])


file() can create a file object, it's a build-in method. You may find someone else will use open(), actually it's an old version method. All parameters are passed in as string.

name: file name;
mode: there're 4 modes: r, w, a and U.
r: read mode;
w: write mode;
a: append mode;
U is a special mode. In Unix/Linux, line break is represented as '\n', while '\r\n' in Windows. U mode is used for support both type of line break.But python prefers '\n' to save these different line break symbols by a tuple.


file's attributes:

closed # if the file has been closed.
encoding # encoding type
mode # open mode
name # file name
newlines # line break mode, it's a tuple
softspace # boolean. indicates whether a space character needs to be printed before another value when using the print statement


file's mehods:

read([size]) # size is the byte length you want to read, read all file if it's not specified.
readline([size]) # read ONE line, maybe less than one line if size is smaller than the length of the line.
readlines([size]) # read several line into a list. size is the whole length.
write(str) # write str into file, there's no line break if you didn't specify.
writelines(seq) # write seq into file
close() # close the file. Although python will close a file while program don't need it anymore, but there's no guarantee. It's better to call this methods by yourselves.
flush() # write buffered content into the file.
fileno() # return a long file tag.
isatty() # is a terminal file(Unix/Linux).
tell() # current position from beginning of the file.
next() # return next line and move the pointer to next line.
seek(offset[,whence]) # move the pointer to offset. Usually calculated from the beginning except whence is specified. 0 beginning, 1 current position, 2 the end. Note: if the open mode is a or a+, the pointer will move to the end after every write operation.
truncate([size]) # cut the file into several segments with specified size, default cut untill reach the current position. If size is bigger than the file size, according to different OS, maybe there's no change, maybe add 0, maybe add random content.